home *** CD-ROM | disk | FTP | other *** search
/ The Complete Utilities To…ka 501 Killer Utilities! / 501 Killer Utilities! (Macworld July 1995).cdr / Programming / RLaB / doc / rlabp.tex < prev   
Encoding:
Text File  |  1995-01-14  |  94.9 KB  |  2,713 lines  |  [TEXT/????]

  1. %% RLaB Primer
  2. %
  3. %% This file documents RLaB, a Vector and Matrix Programming Language
  4. %% Copyright @copyright{} 1992, 1993, 1994 Ian R. Searle
  5. %%
  6. %% Permission is granted to make and distribute verbatim copies of
  7. %% this manual provided the copyright notice and this permission notice
  8. %% are preserved on all copies.
  9. %%
  10. %% Permission is granted to process this file through TeX and print the
  11. %% results, provided the printed document carries a copying permission
  12. %% notice identical to this one except for the removal of this paragraph
  13. %% (this paragraph not being relevant to the printed manual).
  14. %%
  15. %% Permission is granted to copy and distribute modified versions of this
  16. %% manual under the conditions for verbatim copying, provided also that the
  17. %% sections entitled ``Distribution'' and ``General Public License'' are
  18. %% included exactly as in the original, and provided that the entire
  19. %% resulting derived work is distributed under the terms of a permission
  20. %% notice identical to this one.
  21. %%
  22. %% Permission is granted to copy and distribute translations of this manual
  23. %% into another language, under the above conditions for modified versions,
  24. %% except that the sections entitled ``Distribution'' and ``General Public
  25. %% License'' may be included in a translation approved by the author instead
  26. %% of in the original English.
  27. %
  28. % This document copyright
  29. %               Ian R. Searle
  30. %        ians@eskimo.com
  31. % and
  32. %               Phillip Musumeci, Electrical Engineering Department,
  33. %               University College, Australian Defence Force Academy,
  34. %               Canberra A.C.T. 2600, AUSTRALIA.
  35. %
  36. %% For permissions relating to reproduction of this document,
  37. %% see PERMISSIONS below.
  38. %%
  39. %% For corrections and suggestions relating to this document,
  40. %% see SUGGESTIONS below.
  41. %
  42.  
  43. \documentstyle[11pt]{article}
  44.  
  45. \newcommand{\defined}{\buildrel {\triangle}\over =}
  46. \newcommand{\dfn}{\buildrel {\triangle}\over =}
  47. \newcommand{\tends}{\mbox{$\rightarrow$}}
  48. \newcommand{\half}{\mbox{${1 \over 2}$}}
  49.  
  50. %\typeout{RLaB primer v0.1 phillip@ee.adfa.oz.au 22/1/93}
  51.  
  52. \addtolength{\topmargin}{-1.9cm}        % shrink LaTeX's huge margins
  53. \addtolength{\textwidth}{4cm}
  54. \setlength{\textheight}{22.2cm}
  55. \setlength{\parindent}{0in}
  56. \addtolength{\oddsidemargin}{-1.9cm}
  57. \addtolength{\evensidemargin}{-1.9cm}
  58. \setlength{\parskip}{0.25cm}
  59.  
  60. %%
  61. %% Define RLaB logos. They are all the same
  62. %%
  63. \def\RLAB{{\rm R\kern-.16em\lower.5ex\hbox{L}\kern-.25em\raise.3ex
  64.     \hbox{a}\kern-.1emB}\,}
  65. \def\RLaB{{\rm R\kern-.16em\lower.5ex\hbox{L}\kern-.25em\raise.3ex
  66.     \hbox{a}\kern-.1emB}\,}
  67. \def\Rlab{{\rm R\kern-.16em\lower.5ex\hbox{L}\kern-.25em\raise.3ex
  68.     \hbox{a}\kern-.1emB}\,}
  69. \def\rlab{{\rm R\kern-.16em\lower.5ex\hbox{L}\kern-.25em\raise.3ex
  70.     \hbox{a}\kern-.1emB}\,}
  71.  
  72. \begin{document}
  73.  
  74. \begin{titlepage}
  75.  
  76. \begin{center}
  77. {\Huge \rlab\ Primer \\}
  78. {\Large Version 1.0}
  79.  
  80. \vskip 1cm
  81. {\Large Ian R. Searle \& Phillip Musumeci}
  82. \end{center}
  83.  
  84. \vskip 3cm
  85.  
  86. \begin{figure}[h]
  87.   \begin{picture}(350,300)(0,50) % (x-size, y-size) (x-shift, y-shift)
  88.     \special{psfile=logo.ps
  89.              angle=90 hscale=120 vscale=120 voffset=-100 hoffset=700}
  90.     \end{picture}
  91. \end{figure}
  92.  
  93. \vskip 1cm
  94.  
  95. \begin{center}
  96.   The \RLaB\ program is \copyright copyright 1993, 94 Ian R. Searle.\\ This
  97.   document is \copyright copyright 1993, 94 Ian R. Searle \& Phillip Musumeci.
  98. \end{center}
  99.  
  100. \end{titlepage}
  101. \newpage
  102. \tableofcontents
  103. \newpage
  104. \listoffigures
  105. \newpage
  106.  
  107. \setcounter{section}{-1}
  108. %\setcounter{page}{35}
  109.  
  110. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  111. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  112. \section{Primer priming}
  113.  
  114. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  115. \subsection{\RLaB\ is freely available}
  116.  
  117. \RLaB\ stands for Our-Lab, since it is intended to be a freely available
  118. program that anyone can use, and contribute to. To protect this freedom,
  119. copying of the program is protected by the GNU General Public License.
  120.  
  121. The main ftp site is \verb+evans.ee.adfa.oz.au+. The directory
  122. \verb+pub/RLaB+ contains the sources and binary versions for some
  123. machines. On the North American continent \verb+csi.jpl.nasa.gov+
  124. acts as an archive site for \rlab, look in \verb+pub/matlab/RLaB+.
  125.  
  126. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  127. \subsection{Acknowledgments}
  128.  
  129. The availability of ``free'' software, such as GNU Emacs, GNU gcc,
  130. gdb, gnuplot, Plplot, and the Netlib archives has made this project
  131. possible.  The \RLaB\ author thanks both the authors and sponsors of
  132. the GNU, LAPACK, RANLIB, FFTPACK, and Plplot projects.
  133.  
  134. Many individuals have contributed to \rlab\ in various ways. A list of
  135. contributors can be found in the source distribution file
  136. \verb+ACKNOWLEDGMENT+. A special thanks to Phillip Musumeci and
  137. Matthew Wette who have provided FTP sites so that \rlab\ is available
  138. to all.
  139.  
  140. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  141. \subsection{Document reproduction and errors}
  142.  
  143. %% PERMISSIONS
  144.  
  145. The \RLaB\ Primer is freely available. Permission is granted to reproduce
  146. the document in any way providing that it is distributed for free, except
  147. for any reasonable charges for printing, distribution, staff time, etc.
  148. Direct commercial exploitation is not permitted.  Extracts may be made from
  149. this document providing an acknowledgment of the original \LaTeX\ source is
  150. maintained.
  151.  
  152. %% SUGGESTIONS
  153.  
  154. We welcome reports of errors and suggestions for improvement in this
  155. document and also in \Rlab.  Please mail these to {\tt
  156. rlab-list@eskimo.com}. Unfortunately (for you), free software does not earn
  157. quite enough to pay a bribe for each error-free error report received but
  158. do feel free to email them.
  159.  
  160. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  161. \subsection{Requirements}
  162.  
  163. \RLaB\ is written in C. The maths libraries used are written in
  164. Fortran but the use of a publicly available Fortran$\rightarrow$C
  165. converter reduces compiler requirements to C (the conversion tool f2c
  166. is written in C). The library used for data display, PLPLOT, is
  167. publicly available in C source code form for a wide variety of
  168. platforms. This makes the whole \RLaB\ package a good candidate for
  169. porting onto platforms with C, especially GNU C.
  170.  
  171. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  172. \subsection{How to Read This Primer}
  173.  
  174. This primer has intentionally been kept short, so you should be able
  175. to read all of it without too much effort. Probably the best way to
  176. read this primer is to do so sitting at a computer, trying the
  177. examples as you encounter them.
  178.  
  179.  
  180. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  181. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  182. \section{Introduction} \label{sect-intro}
  183.  
  184. \RLaB\ brings the power of stable matrix maths tools plus a stable data
  185. plotting facility together in a form that is freely available and ready to
  186. be compiled and used on a variety of common computer systems. \RLaB\ allows
  187. you to experiment with complex matrix maths in an interactive environment.
  188. Because you enter commands at a high (mathematical) level, you can
  189. concentrate on figuring out your solution and hopefully avoid becoming
  190. bogged down in low level implementation details. By minimising the effort
  191. required to implement algorithms, it is hoped that you will be more willing
  192. to discard old programs when confronted by better algorithms that warrant
  193. use.
  194.  
  195. \RLaB\ uses a structured language\footnote{These days, computer
  196. languages do look very similar but we will try to point out a few {\em
  197. useful} similarities!} which will be familiar to users of C and also
  198. the Wirth-inspired languages such as Pascal and Modula.  An \RLaB\
  199. program is a file containing a sequence of commands or instructions
  200. that you could also enter from your terminal---these instructions
  201. might perform a calculation and assign the result to a variable, or
  202. call a function which returns a result which you display on your
  203. terminal, and so on. Functions can be either built-in or user-defined.
  204. In fact, the only form of ``subprogram'' in \RLaB\ is the function
  205. and, just like in C, a function returns a single item as its answer.
  206. Data storage declared in the main routine of your program is stored on
  207. a global symbol table, and is available to all of your subprogram
  208. functions. By default, data used within functions is local to the
  209. function. Such local function storage exists only for the duration of
  210. the function call, in a way similar to variables declared locally
  211. within Pascal procedures.  Comments can be appended to any line in
  212. your program by using a special symbol at the start of the
  213. comment---this is similar to Fortran and C++, and avoids the possible
  214. pitfall of ``run away'' comments which might be familiar to Pascal
  215. users.  Overall, the language syntax is perhaps closest to C but if
  216. you have ever programmed in C or Pascal, you will soon be at ease with
  217. \RLaB.
  218.  
  219. \RLaB\ features strongly typed objects but with the emphasis on
  220. usefulness, not on pedantics. In \RLaB\, we talk about the {\em class}
  221. of an object and the available classes include numeric, string,
  222. function, and list.  The first class of object, {\em numeric},
  223. encompasses numeric scalars, vectors, and matrices, and should be
  224. familiar to the matrix maths user. The remaining classes borrow
  225. concepts, and implementation details from other languages such as C.
  226.  
  227. It is worth noting that a function can be thought of as just another
  228. object---this means that when you come to write your own functions
  229. that use input parameters, you will enjoy the flexibility of being
  230. able to pass in other functions as well as data as input to your
  231. function. Another feature of functions as implemented in \RLaB\ is
  232. that they can call themselves---anyone who has written a program to
  233. calculate factorials will appreciate the elegance that recursion can
  234. bring to some programming solutions.
  235.  
  236. Having whetted your appetite, this primer aims to get you started with
  237. \RLaB\ as both an interactive tool and as a programming language. The
  238. ideal approach is for you to read (or re-read) this document with an
  239. \RLaB\ session staring up at you. After showing you how to run \RLaB\
  240. and get on-line help, we describe data types before moving back to a
  241. ``hands on'' description of basic operations.  Program structure is
  242. then described and you will see how to write your own functions. As
  243. \RLaB\ comes with quite a few handy functions already built-in, we
  244. give examples of their use including the plot function at which point
  245. we hope you will be able to start using \RLaB\ to develop your own
  246. programs.
  247.  
  248. % and you will find the quick reference tables in the appendices most
  249. % useful.
  250.  
  251. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  252. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  253.  
  254. \section{Starting to use \RLaB}
  255.  
  256. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  257.  
  258. \subsection{How to run it}
  259.  
  260. A properly installed \RLaB\ can be started on your terminal by entering
  261.  
  262. \begin{verbatim}
  263. $ rlab
  264. \end{verbatim}
  265.  
  266. where typewriter-style dark text is meant to represent the text you
  267. would see sitting in front of a display terminal. The first character
  268. on the input line is always the prompt, in this case a Bourne-shell
  269. prompt. The text following is what the user enters. Text echoed by a
  270. program is not preceded by any prompt.
  271.  
  272. \RLaB\ will start with a message similar to:
  273.  
  274. \begin{verbatim}
  275. Welcome to RLaB. New users type `help INTRO'
  276. RLaB version 1.0 Copyright (C) 1992, 93, 94 Ian Searle
  277. RLaB comes with ABSOLUTELY NO WARRANTY; for details type `help WARRANTY'
  278. This is free software, and you are welcome to redistribute it under
  279. certain conditions; type `help CONDITIONS' for details
  280. >
  281. \end{verbatim}
  282.  
  283. The \verb+>+ symbol on the last line next to the cursor is the \RLaB\ 
  284. command prompt.  At this point, users should take the advice offered and
  285. be usefully distracted from this primer by {\em actually reading} the
  286. information available from {\tt help INTRO} - do not worry if you cannot
  287. follow it yet. After you have read each screenful, press {\tt SPACE} (i.e.
  288. the space bar) to see further screens of information.
  289.  
  290.    At this point it is only fair to tell you how to stop it. To stop a
  291.    \rlab session you can type \verb+quit+ at the \rlab prompt. On Unix
  292.    systems an \verb+EOF+ or \verb+^d+ (control-d) will also stop
  293.    \rlab. 
  294.  
  295. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  296. \subsection{Help}
  297.  
  298. To get a taste of the functions for which help is available, enter
  299.  
  300. \begin{verbatim}
  301. > help
  302. \end{verbatim}
  303.  
  304. The first group of topics lists functions and special help topics
  305. that are built into \RLaB. The special topics have names in upper case and
  306. are of a general nature. Lawyers recommend that you {\em now} read the help
  307. on topics {\tt CONDITIONS} and {\tt WARRANTY} by entering
  308.  
  309. \begin{verbatim}
  310. > help CONDITIONS
  311. \end{verbatim}
  312. \begin{verbatim}
  313. > help WARRANTY
  314. \end{verbatim}
  315.  
  316. The subsequent topics refer to commands that have been written in
  317. \RLaB\ script files, which we refer to as ``R-files''. These R-files
  318. are stored in directories, which the \verb+help+ command searches. The
  319. help files in the {\em \ldots /rlib} directory come as a standard part of
  320. \RLaB, and the remainder refer to local R-files that have been setup
  321. for you by whoever installed your \RLaB. 
  322.  
  323. In general, the functions listed in the first group are the most efficient
  324. as they are compiled into the core of \RLaB. In contrast, \RLaB's R-files
  325. have the extra overhead of reading and interpretation before they are
  326. executed. This lower efficiency associated with R-file interpretation is
  327. traded for the benefit of being able to write your own features into \RLaB.
  328. If an R-file feature is really useful, it can be added to the core \RLaB\
  329. program since you have the source code\footnote{Dynamic linking is
  330. part of the plan for a future release}.
  331.  
  332. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  333. \subsection{Simple calculations} \label{simple-calc}
  334.  
  335. \RLaB\ is designed for mathematical calculations so let's do some. The four
  336. basic arithmetic operators have symbols {\verb|+, -, *, /|} representing
  337. addition, subtraction, multiplication, and division respectively. Now enter
  338. some one line expressions as shown here:
  339.  
  340. \begin{verbatim}
  341. > 2*4
  342.         8
  343. > 1/2
  344.       0.5
  345. > 1+11
  346.        12
  347. > 1-11
  348.       -10
  349. > 1*2/3+4-5
  350.    -0.333
  351. > 1/0
  352.       inf
  353. > 0/(1/0)
  354.         0
  355. > 0/0
  356.       NaN
  357. \end{verbatim}
  358.  
  359. The $5^{th}$ expression illustrates compliance with the usual operator
  360. hierarchy and then we observe that \RLaB\ can handle
  361. exceptions\footnote{The ability to properly handle floating point
  362. exceptions is dependent upon the capabilities of the hardware and
  363. operating system, as well as the interests of the person installing
  364. \RLaB\ .} such as when $\infty$ (\verb+inf+) is a result or an input to
  365. further calculation; and also ``not-a-number'' (\verb+NaN+).  \RLaB\ can use
  366. complex numbers as well as real numbers so now try
  367.  
  368. \begin{verbatim}
  369. > 1/1i
  370.         0 - 1i
  371. > 1/1i + 1/1j
  372.         0 - 2i
  373. > 1/1i * 1/1j
  374.        -1
  375. > 1/1i/1j
  376.        -1
  377. \end{verbatim}
  378.  
  379. where we see that {\tt i} or {\tt j} can represent the complex
  380. number $\sqrt{-1}$. No four function calculator is complete without a
  381. memory so now we look at how to store results in a variable.
  382.  
  383. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  384. \subsection{Variable assignment and display}
  385.  
  386. In \RLaB, variables can have names of any length containing most printable
  387. characters including $\{ a \ldots z , A \ldots Z , \_ \}$. You will observe
  388. that we have to exclude special characters such as {\verb|+, -, *, /|} and
  389. the {\tt SPACE} character. The actual assignment operator symbol is ``=''
  390. and an assignment statement looks like
  391.  
  392. \begin{verbatim}
  393.                 variable_name = expression_to_evaluate
  394. \end{verbatim}
  395.  
  396. and an example is
  397.  
  398. \begin{verbatim}
  399. > radius=2
  400.  radius =
  401.         2
  402. > circumference=2 * pi * radius
  403.  circumference =
  404.      12.6
  405. \end{verbatim}
  406.  
  407. where a variable {\tt radius} is created and initialised with the
  408. real value 2, and then a variable {\tt circumference} is created and filled
  409. with the result of evaluating the right hand side of the equation. To see
  410. the value of either of these variables, just enter their name and
  411. \RLaB\ will print their value.  For a description of variable names, please read
  412. the help on {\tt VARIABLES}.
  413.  
  414. As you have probably noticed by now, the result of each expression is
  415. automatically printed to the screen. This feature can be controlled by
  416. using the `\verb+;+' character. Terminating an expression with a
  417. `\verb+;+' will suppress printing of the result. Likewise, terminating
  418. an expression with the `\verb+?+' is an explicit way to force printing.
  419.  
  420. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  421. \subsection{User Interface: command recall \& editing}
  422.  
  423. Command line recall and editing is very useful for correcting command
  424. errors or to allow your commands to evolve.  \RLaB\ provides a command
  425. recall and edit facility modeled on (and sometimes actually using) the GNU
  426. readline facility. If you are familiar with GNU emacs or the GNU bash
  427. shell, then try entering {\tt C-p} to scroll back through previous commands
  428. ({\tt C-p} means hold down the {\tt control} key and press {\tt p}).  If
  429. this is successful, test the standard character and word editing commands
  430. to modify previous entries - if it works, skip to section
  431. \ref{sec:objects}.
  432.  
  433. However, if the word GNU just means ``any of several African antelopes
  434. constituting the genus {\em Connochaetes} ...''\footnote{Australian
  435. Macquarie dictionary, ISBN: 0-949757-23-3.} but your keyboard does have the
  436. arrow keys \{\ $\leftarrow\ \uparrow\ \downarrow\ \rightarrow\ $\}, then
  437. you might still be able to take advantage of command line recall and
  438. editing.  Try typing the $\uparrow$ key to see if any previous \RLaB\
  439. commands are displayed - if they are, then confirm that $\downarrow$ also
  440. displays more recent commands and then try horizontal cursor movement with
  441. the \{\ $\leftarrow\ \rightarrow\ $\} and try some editing with the delete
  442. key.  Typing {\tt C-d} ought to delete the character beneath the cursor.
  443. When a new command has been created from an old, enter it in the usual way
  444. by pressing {\tt RETURN}.  If this has worked for you, skip the remainder
  445. of this section (and count yourself lucky that we weren't describing a
  446. graphical user interface in one paragraph).
  447.  
  448. If your keyboard is missing the arrow keys but {\tt C-p} did cause previous
  449. commands to pop up on the \RLaB\ command line, you will find that \{\
  450. $\leftarrow\ \uparrow\ \downarrow\ \rightarrow\ $\} are the same as \{\
  451. {\tt C-b C-p C-n C-f}\ \} - think of b for backwards, p for previous, n for
  452. next, and f for forward.
  453.  
  454. Irrespective of what keystrokes you use for editing, the C-y keystroke will
  455. restore text previously deleted. If you were unable to scroll back through
  456. any previous commands (that you had just entered), then your \RLaB\ may have
  457. been built without command line editing - this is unlucky.  As command
  458. line editing is such a useful feature, you should consider getting a
  459. better version of \RLaB\ if possible. 
  460.  
  461. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  462. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  463.  
  464. \section{Objects---Basic Data Structures} \label{sec:objects}
  465.  
  466. In the most general form, an object in \RLaB\ can be data or a
  467. function. It is even possible to construct an object that contains
  468. both data {\em and} functions - a fact that no doubt excites the
  469. hormones in the modern day object oriented programmer. We are going to
  470. discuss basic data types before looking at how data can be ``grouped''
  471. together for some useful purpose. We will also work through some
  472. simple examples that manipulate data but first, what does \Rlab\
  473. regard as data?
  474.  
  475. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  476.  
  477. \subsection{Data Types}
  478.  
  479. There are three {\em fundamental} types of data that you manipulate in
  480. \RLaB: the string; the real number; and the complex number.  As we have
  481. seen in section \ref{simple-calc}, it is straight-forward to
  482. manipulate numerical quantities. Characters are available in the form
  483. of strings which can contain 0 or more characters. In line with a
  484. philosophy to ``keep it simple'', \RLaB\, which is primarily concerned
  485. with numerical computation, has no special way to handle a single
  486. character\footnote{And also one less data type that you need to learn
  487. about.}. To enter a string, enclose the characters inside quotes like
  488. \verb+"this"+ e.g.
  489.  
  490. \begin{verbatim}
  491. > "Hello world"
  492. Hello world
  493. \end{verbatim}
  494.  
  495. Just as a number was previously stored in a variable, the same can be done
  496. with a string of characters. To place a string into a variable, you
  497. could enter a statement such as
  498.  
  499. \begin{verbatim}
  500. > hw = "Hello world"
  501. Hello world
  502. \end{verbatim}
  503.  
  504. and the value of variable \verb+hw+ may be printed out by entering
  505.  
  506. \begin{verbatim}
  507. > hw
  508. Hello world
  509. \end{verbatim}
  510.  
  511. The observant reader might be wondering what has happened to the
  512. boolean data type? In \RLaB, {\em true} and {\em false} are
  513. represented by the integers 1 and 0. Just as the data type char can be
  514. handled as a rather small string (length=1), so the data type boolean
  515. (or logical) can be handled by small numbers (value=0,1). We have now
  516. met the 3 fundamental types of data processed in \RLaB\ and it is now
  517. possible to understand a little more about how data structures and
  518. functions are organised within \RLaB.
  519.  
  520. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  521. \subsection{Object Hierarchy}
  522.  
  523. Scan your eyes down over Figure \ref{fig:objects} which shows the
  524. hierarchical structure of objects in \RLaB\ - we shall now describe
  525. this figure from the bottom up (ignoring lists until a little
  526. later). Not all objects are created in the same way and what you can do with
  527. or to them depends on their {\em class}. Items of class {\em function}
  528. contain program instructions which is one form of data or
  529. information. Items of class {\em numeric}, and {\em string} contain
  530. data that \RLaB\ instructions can manipulate.
  531.  
  532. \begin{figure}[htbp]
  533.   \begin{picture}(350,300)(0,25) % (x-size, y-size) (x-shift, y-shift)
  534.     \special{psfile=object.ps
  535.              angle=0 hscale=65 vscale=65 voffset=-55 hoffset=40}
  536.     \end{picture}
  537. \caption{\RLaB objects} \label{fig:objects}
  538. \end{figure}
  539.  
  540. A numeric class item can store a real or complex number.  An item of
  541. class string contains a null-terminated string of character(s). When
  542. we want to access or create an array of items, we use an array syntax
  543. that is the same for both string and numeric classes.
  544.  
  545. It is often helpful to a programmer to group together unlike data into
  546. a single object - this is the purpose of the class list.  We are not
  547. going to describe it in great detail here except to point out that it
  548. serves a similar role to a record in Pascal or a structure in C, but
  549. with a somewhat more flexible access mechanism. Note that lists can
  550. contain any of the aforementioned objects, even another list.
  551.  
  552. One thing that you can always do with any item is ask \RLaB\ what its
  553. class is. For example, \RLaB\ has a built-in command to calculate the
  554. sin of an angular quantity - asking \RLaB\ about it gives the
  555. following response
  556.  
  557. \begin{verbatim}
  558. > class( sin )
  559. function
  560. \end{verbatim}
  561.  
  562. From the size of the list of topics that help is available on, you
  563. probably realise that there are many built-in functions in \RLaB\ -
  564. expect gratuitous use of these functions as further examples are
  565. given.  Remember that you can find out about any function by typing
  566. {\tt help} {\em function-name}. We are particularly interested in
  567. exploring the use of \RLaB\ as a computation tool so now we describe
  568. further numeric operations. 
  569.  
  570. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  571. \subsection{Numerics}
  572.  
  573.    The \RLaB\ numeric class includes objects of type real and
  574.    complex. The numeric object also encompasses objects of scalar,
  575.    vector, or matrix dimension. If you want to, you can think of all
  576.    numeric objects as matrices. Thus, a vector is simply a 1-by-N
  577.    matrix, and a scalar is a 1-by-1 matrix. Since the numeric object
  578.    is most commonly used, it will get the most coverage.
  579.  
  580. \subsubsection{Matrix Creation }
  581.  
  582.    The simplest way to create a matrix is to type it in at the command
  583.    line: 
  584.  
  585. \begin{verbatim}
  586. > m = [ 1, 2, 3; 4, 5, 6; 7, 8, 9 ]
  587.  m =
  588.         1          2          3  
  589.         4          5          6  
  590.         7          8          9  
  591. \end{verbatim}
  592.  
  593.    In this context the `\verb+[ ]+' signal \Rlab\ that a matrix should
  594.    be created. The inputs (or arguments) for matrix creation are
  595.    whatever is inside the `\verb+[ ]+'. The rows of the matrix are
  596.    delimited with `\verb+;+' and the elements of each row are
  597.    delimited with `\verb+,+'.
  598.  
  599.    Users can use most any expression when creating matrix elements.
  600.    Other matrices, function evaluations, and arithmetic operations are
  601.    allowed when creating matrix elements. In the next example, we will
  602.    create a direction cosine matrix using the built-in trigonometric
  603.    functions within the `\verb+[ ]+'.
  604.  
  605. \begin{verbatim}
  606. > a = 45*(2*pi)/360
  607.  a =
  608.     0.785
  609. > A = [ cos(a), sin(a); -sin(a), cos(a) ]
  610.  A =
  611.     0.707      0.707  
  612.    -0.707      0.707  
  613. \end{verbatim}
  614.  
  615.    Matrices can also be read from disk-files. The functions
  616.    \verb+read+, \verb+readb+ and \verb+readm+ can read matrix values
  617.    from a file. The \verb+read+ function uses a special ASCII text
  618.    file format, and is capable of reading not only matrices, but
  619.    strings, and lists as well. Since the file can contain many data
  620.    objects, and their variable names, \verb+read+ is used like:
  621.  
  622. \begin{verbatim}
  623. > read ( "file.dat" );
  624. \end{verbatim}
  625.  
  626.    The variables are read from \verb+file.dat+ and installed in the
  627.    global-symbol-table.
  628.  
  629.    The \verb+readb+ function works like \verb+read+, except it reads
  630.    binary files for greater efficiency. The binary files created with
  631.    \verb+writeb+ are portable across computers that use IEEE floating
  632.    point format.
  633.  
  634.    The \verb+readm+ function reads a text file that contains
  635.    white-space separated columns of numbers. \verb+readm+ is most
  636.    often used to read in data created by other programs. Since
  637.    \verb+readm+ is only capable of reading in one matrix per file, and
  638.    no variable name information is available, \verb+readm+ is used
  639.    like:
  640.  
  641. \begin{verbatim}
  642. > a = read ( "a.dat" );
  643. \end{verbatim}
  644.  
  645. \subsubsection{Vector Creation}
  646.  
  647.    Although there is no distinct vector type in \RLaB\ , you can
  648.    pretend that there is. If your algorithm, or program does not need
  649.    two dimensional arrays, then you can use matrices as singly
  650.    dimensioned arrays.
  651.  
  652.    When using vectors, or single dimension arrays, row matrices are
  653.    created. The simplest way to create a vector is with the `\verb+:+'
  654.    operator(s), that is `\verb+start:end:inc+'. The leftmost operand,
  655.    \verb+start+, specifies the starting value, the second operand,
  656.    \verb+end+, specifies the last value. The default increment, or
  657.    spacing, is 1.  A third optional operand, \verb+inc+, can be used
  658.    to specify any increment.
  659.  
  660. \begin{verbatim}
  661. > v = 1:4
  662.  v =
  663.         1          2          3          4  
  664. \end{verbatim}
  665.  
  666. \subsubsection{Matrix Attributes}
  667.  
  668.    Matrix attributes, such as number of rows, number of columns, total
  669.    number of elements, are accessible in several ways. All attributes
  670.    are accessible through function calls, for example:
  671.  
  672. \begin{verbatim}
  673. > a = rand(3,5);
  674. > show (a)
  675.    name:      a     
  676.    class:     num   
  677.    type:      real  
  678.      nr:      3     
  679.      nc:      5     
  680. > size (a)
  681.         3          5  
  682. > class (a)
  683. num
  684. > type (a)
  685. real
  686. \end{verbatim}
  687.  
  688.    Matrix attributes are also accessible via a shorthand notation:
  689.  
  690. \begin{verbatim}
  691. > a.nr
  692.         3
  693. > a.nc
  694.         5
  695. > a.n
  696.        15
  697. > a.class
  698. num
  699. > a.type
  700. real
  701. \end{verbatim}
  702.   
  703.    Note that these matrix attributes are ``read-only''. In other
  704.    words: assignment to \verb+a.nr+ is pointless. In fact it will
  705.    destroy the contents of \verb+a+ and create a list with element
  706.    named \verb+nr+. If you wish to change a matrix attribute, you must
  707.    do so by changing the data in \verb+a+. For example: if you want to
  708.    make \verb+a+ complex:
  709.  
  710. \begin{verbatim}
  711. > a = a + zeros (size (a))*1i;
  712. > show(a)
  713.    name:      a
  714.    class:     num
  715.    type:      complex
  716.      nr:      3
  717.      nc:      5
  718. \end{verbatim}
  719.  
  720.    If you want to change the number of rows, or columns of \verb+a+:
  721.  
  722. \begin{verbatim}
  723. > a = reshape (a, 1, 15);
  724. > show(a)
  725.    name:      a
  726.    class:     num
  727.    type:      complex
  728.      nr:      1
  729.      nc:      15
  730. \end{verbatim}
  731.  
  732. \subsubsection{Element Referencing}
  733.  
  734.    Any expression that evaluates to a matrix can have its elements
  735.    referenced. The simplest case occurs when a matrix has been created
  736.    and assigned to a variable. One can reference single elements, or
  737.    one can reference full or partial rows and/or columns of a matrix.
  738.    Element referencing is performed via the `{\verb+[ ]+}' operators,
  739.    using the `\verb+;+' to delimit row and column specifications, and
  740.    the `\verb+,+' to delimit individual row or column specifications.
  741.  
  742.    To reference a single element:
  743.  
  744. \begin{verbatim}
  745. > a = [1,2,3; 4,5,6; 7,8,9];
  746. > a [ 2 ; 3 ]
  747.         6
  748. \end{verbatim}
  749.  
  750.    To reference an entire row, or column:
  751.  
  752. \begin{verbatim}
  753. > a [ 2 ; ]
  754.         4          5          6  
  755. > a [ ; 3 ]
  756.         3  
  757.         6  
  758.         9  
  759. \end{verbatim}
  760.  
  761.    To reference a sub-matrix:
  762.  
  763. \begin{verbatim}
  764. > a [ 2,3 ; 1,2 ]
  765.         4          5  
  766.         7          8  
  767. \end{verbatim}
  768.  
  769.    As stated previously, any expression that evaluates to a matrix can
  770.    have its elements referenced. A very common example is getting the
  771.    row or column dimension of a matrix:
  772.  
  773. \begin{verbatim}
  774. > size (a)[1]
  775.         3
  776. \end{verbatim}
  777.  
  778.    In the previous example the function \verb+size+ returns a
  779.    two-element matrix, from which we extract the 1st element (the
  780.    value of the row dimension). Note that we referenced the return
  781.    value (a matrix) as if it were a vector. Referencing matrices in
  782.    ``vector-fashion'' is allowed with all matrices. When
  783.    vector-indexing is used, the matrix elements are referenced in
  784.    column order. As with matrix indexing, a combination of vector
  785.    elements can be referenced: 
  786.  
  787. \begin{verbatim}
  788. > a[3]
  789.         7
  790. > a[3,4,9]
  791.         7          2          9  
  792. \end{verbatim}
  793.  
  794. \subsubsection{Assignment}
  795.  
  796.    Matrices can be assigned to in whole or in part. We have shown
  797.    complete matrix assignment in the examples of the last few pages. In
  798.    the same way that matrix elements can be referenced singly, or in
  799.    groups, matrices can have single elements re-assigned, or groups of
  800.    elements re-assigned. The result of an assignment expression is the
  801.    left-hand-side (LHS). This is more convenient when working
  802.    interactively, and when creating intermediate function arguments.
  803.  
  804. \begin{verbatim}
  805. > a[2;2] = 200
  806.  a =
  807.         1          2          3  
  808.         4        200          6  
  809.         7          8          9  
  810. > a[2,3;2,3] = [200,300;300,400]
  811.  a =
  812.         1          2          3  
  813.         4        200        300  
  814.         7        300        400  
  815. \end{verbatim}
  816.  
  817.    The row and column dimensions of the matrices on the RHS, and the
  818.    matrix description within the `\verb+[ ]+' must have the same
  819.    dimensions.
  820.  
  821.  
  822. \subsubsection{Matrix Operations}
  823.  
  824.    The usual mathematical operators {\verb|+,-,*,/|} operate on
  825.    matrices as well as scalars. For {\verb+A binop B+}:
  826.  
  827.    \begin{description}
  828.      \item[{\tt +}] Does element-by-element addition of two matrices.
  829.               The row and column dimensions of both \verb+A+ and
  830.               \verb+B+ must be the same. An exception to the
  831.               aforementioned rule occurs when either \verb+A+ or
  832.               \verb+B+ is a 1-by-1 matrix; in this case a
  833.               scalar-matrix addition operation is performed.
  834.  
  835.      \item[{\tt -}] Does element-by-element subtraction of two matrices.
  836.               The row and column dimensions of both \verb+A+ and
  837.               \verb+B+ must be the same. An exception to the
  838.               aforementioned rule occurs when either \verb+A+ or
  839.               \verb+B+ is a 1-by-1 matrix; in this case a
  840.               scalar-matrix addition operation is performed.
  841.  
  842.      \item[{\tt *}] Performs matrix multiplication on the two
  843.               operands.  The column dimension of {\verb+A+} must match
  844.               the row dimension of {\verb+B+}. An exception to the
  845.               aforementioned rule occurs when either \verb+A+ or
  846.               \verb+B+ is a 1-by-1 matrix; in this case a
  847.               scalar-matrix multiplication is performed.
  848.  
  849.      \item[{\tt /}] Performs matrix ``right-division'' on its operands.
  850.               The matrix right-division (\verb+B/A+) can be thought of
  851.               as {\verb+B*inv (A)+}. The column dimensions of \verb+A+
  852.               and \verb+B+ must be the same. Internally right division
  853.               is the same as ``left-division'' with the arguments
  854.               transposed. 
  855.  
  856.         \[ B / A = ( A^T \setminus B^T )^T \]
  857.  
  858.               The exception to the aforementioned dimension rule
  859.               occurs when \verb+A+ is a 1-by-1 matrix; in this case a
  860.               matrix-scalar divide occurs.
  861.  
  862.    \end{description}
  863.  
  864.    Additionally, \RLaB\ has several other operators that function on
  865.    matrix operand(s). 
  866.  
  867.  
  868.    \begin{description}
  869.      \item[{\tt .+}] Performs element-by-element addition on
  870.               its operands. The operands must have the same row and
  871.               column dimensions. {\em Unless}:
  872.  
  873.           \begin{itemize}
  874.  
  875.         \item \verb+A+ or \verb+B+ is a 1x1. In this case the
  876.         operation is performed element-by-element over the
  877.         entire matrix. The result is a MxN matrix.
  878.  
  879.         \item \verb+A+ or \verb+B+ is a 1xN. and the other is
  880.         MxN. In this instance the operation is performed
  881.         element-by-element fashion for each row in the
  882.         matrix. The result is a MxN matrix.
  883.  
  884.         \item \verb+A+ or \verb+B+ is a Nx1. and the other is
  885.         NxM. In this instance the operation is performed
  886.         element-by-element fashion for each column in the
  887.         matrix. The result is a NxM matrix.
  888.  
  889.               \end{itemize}
  890.  
  891.      \item[{\tt .-}] Performs element-by-element subtraction on
  892.               its operands. The operands must have the same row and
  893.               column dimensions. {\em Unless}:
  894.  
  895.           \begin{itemize}
  896.  
  897.         \item \verb+A+ or \verb+B+ is a 1x1. In this case the
  898.         operation is performed element-by-element over the
  899.         entire matrix. The result is a MxN matrix.
  900.  
  901.         \item \verb+A+ or \verb+B+ is a 1xN. and the other is
  902.         MxN. In this instance the operation is performed
  903.         element-by-element fashion for each row in the
  904.         matrix. The result is a MxN matrix.
  905.  
  906.         \item \verb+A+ or \verb+B+ is a Nx1. and the other is
  907.         NxM. In this instance the operation is performed
  908.         element-by-element fashion for each column in the
  909.         matrix. The result is a NxM matrix.
  910.  
  911.               \end{itemize}
  912.  
  913.      \item[{\tt .*}] Performs element-by-element multiplication on
  914.               its operands. The operands must have the same row and
  915.               column dimensions. {\em Unless}:
  916.  
  917.           \begin{itemize}
  918.  
  919.         \item \verb+A+ or \verb+B+ is a 1x1. In this case the
  920.         operation is performed element-by-element over the
  921.         entire matrix. The result is a MxN matrix.
  922.  
  923.         \item \verb+A+ or \verb+B+ is a 1xN. and the other is
  924.         MxN. In this instance the operation is performed
  925.         element-by-element fashion for each row in the
  926.         matrix. The result is a MxN matrix.
  927.  
  928.         \item \verb+A+ or \verb+B+ is a Nx1. and the other is
  929.         NxM. In this instance the operation is performed
  930.         element-by-element fashion for each column in the
  931.         matrix. The result is a NxM matrix.
  932.  
  933.               \end{itemize}
  934.  
  935.      \item[{\tt ./}] Performs element-by-element division on its
  936.               operands. The operands must have the same row and column
  937.               dimensions. {\em Unless}:
  938.  
  939.           \begin{itemize}
  940.  
  941.         \item \verb+A+ or \verb+B+ is a 1x1. In this case the
  942.         operation is performed element-by-element over the
  943.         entire matrix. The result is a MxN matrix.
  944.  
  945.         \item \verb+A+ or \verb+B+ is a 1xN. and the other is
  946.         MxN. In this instance the operation is performed
  947.         element-by-element fashion for each row in the
  948.         matrix. The result is a MxN matrix.
  949.  
  950.         \item \verb+A+ or \verb+B+ is a Nx1. and the other is
  951.         NxM. In this instance the operation is performed
  952.         element-by-element fashion for each column in the
  953.         matrix. The result is a NxM matrix.
  954.  
  955.               \end{itemize}
  956.  
  957.      \item[$\setminus$] Performs matrix ``left-division''. Given
  958.               operands {\verb+A\B+} matrix left division is the
  959.               solution to the set of equations $Ax = B$. If $B$ has
  960.               several columns, then each column of $x$ is a solution
  961.               to {\verb+A*x[;i] = B[;i]+}. The row dimensions of
  962.               \verb+A+ and \verb+B+ must agree.
  963.  
  964.      \item[$.\setminus$] Performs element-by-element left-division.
  965.               Element-by-element left-division is provided for
  966.               symmetry, and is equivalent to \verb+B./A+. The row and
  967.               column dimensions of \verb+A+ and \verb+B+ must agree,
  968.               {\em unless}:
  969.  
  970.           \begin{itemize}
  971.  
  972.         \item \verb+A+ or \verb+B+ is a 1x1. In this case the
  973.         operation is performed element-by-element over the
  974.         entire matrix. The result is a MxN matrix.
  975.  
  976.         \item \verb+A+ or \verb+B+ is a 1xN. and the other is
  977.         MxN. In this instance the operation is performed
  978.         element-by-element fashion for each row in the
  979.         matrix. The result is a MxN matrix.
  980.  
  981.         \item \verb+A+ or \verb+B+ is a Nx1. and the other is
  982.         NxM. In this instance the operation is performed
  983.         element-by-element fashion for each column in the
  984.         matrix. The result is a NxM matrix.
  985.  
  986.               \end{itemize}
  987.  
  988.      \item[${}^\wedge{}$] {\verb+A^B+} raises \verb+A+ to the \verb+B+
  989.               power. When \verb+A+ is a matrix, and \verb+B+ is an
  990.               integer scalar, the operation is performed by successive
  991.               multiplications. When \verb+B+ is not an integer, then
  992.               the operation is performed via \verb+A+'s eigenvalues
  993.               and eigenvectors. The operation is not allowed if
  994.               \verb+B+ is a matrix.
  995.  
  996.      \item[${.}^\wedge{}$] {\verb+A.^B+} raises \verb+A+ to the
  997.               \verb+B+ power in an element-by-element fashion. Either
  998.               \verb+A+ or \verb+B+ can be matrix or scalar. If both
  999.               \verb+A+ and \verb+B+ are matrix, then the row and
  1000.               column dimensions must agree.
  1001.  
  1002.      \item[{\tt '}] This unary operator performs the matrix transpose
  1003.               operation. \verb+A'+ swaps the rows and columns of A.
  1004.               For a matrix with complex elements a complex conjugate
  1005.               transpose is performed.
  1006.  
  1007.      \item[{\tt .'}] This unary operator performs the matrix
  1008.               transpose operation. \verb+A.'+ swaps the rows and
  1009.               columns of A.  The difference between \verb+'+ and
  1010.               \verb+.'+ is only apparent when \verb+A+ is a complex
  1011.               matrix; then \verb+A.'+ does not perform a complex
  1012.               conjugate transpose.
  1013.  
  1014.    \end{description}
  1015.  
  1016.    Several details are important to note:
  1017.  
  1018.    \begin{itemize}
  1019.  
  1020.      \item The two character operators are just that, two characters. White
  1021.            space, or any other character in between the two symbols is
  1022.            an error, or may be interpreted differently.
  1023.  
  1024.      \item The expression \verb+2./A+ is {\bf not} interpreted as
  1025.            \verb+2. /A+. \Rlab\ is smart enough to group the period with
  1026.            the `\verb+/+'.
  1027.  
  1028.    \end{itemize}
  1029.  
  1030. \subsubsection{Matrix Relational Operations}
  1031.  
  1032.    The way matrices can be used within if-statement tests is special.
  1033.    The result of a matrix relational test, such as \verb+A == B+, is a
  1034.    matrix the same size as \verb+A+ and \verb+B+ filled with ones and
  1035.    zeros according to the result of an element-by-element test. If
  1036.    either of the operands is scalar, or a 1-by-1 matrix, then the
  1037.    element-by-element test is performed as before, by using the scalar
  1038.    value repeatedly. For example.
  1039.  
  1040. \begin{verbatim}
  1041. > a = [1, 2, 3; 4, 5, 6; 7, 8, 9];
  1042. > b = a';
  1043. > a == b
  1044.         1          0          0  
  1045.         0          1          0  
  1046.         0          0          1  
  1047. > a >= 5
  1048.         0          0          0  
  1049.         0          1          1  
  1050.         1          1          1  
  1051. \end{verbatim}
  1052.  
  1053.    \RLaB\ if-tests do not accept matrices. The built-in functions
  1054.    \verb+any()+ and \verb+all()+ can be used in combination with
  1055.    relational and logical tests to conditionally execute statements
  1056.    based upon matrix properties. For example: perform a test that
  1057.    returns true or false (0 or 1) if \verb+a+ contains the value 4.
  1058.  
  1059. \begin{verbatim}
  1060. > any ( any (a == 4))
  1061. \end{verbatim}
  1062.  
  1063.    The function \verb+any()+ returns true if any of the element(s) of
  1064.    its argument are non-zero. The function \verb+all()+ returns true
  1065.    if all of the element(s) of its argument are non-zero. Note that
  1066.    \verb+any+ is used twice; this is because \verb+any+ is a
  1067.    vector-oriented function. This will be discussed later.
  1068.  
  1069. \subsubsection{Examples}
  1070.  
  1071.    Now it is time for a few illustrative examples \ldots
  1072.  
  1073.    Suppose you are learning about normal-equations, orthogonal
  1074.    transformations, QR decompositions, etc.\footnote{You've been
  1075.    reading Kahaner, Moler, and Nash ``Numerical Methods and Software''
  1076.    for example.} You have read the proper sections in your text(s), and
  1077.    you want to try your hand at it to see if you really understand it.
  1078.  
  1079.    First you create an over-determined coefficient matrix, 3
  1080.    parameters, and 5 equations (\verb+a+). Then you create an
  1081.    observation matrix (\verb+b+):
  1082.  
  1083. \begin{verbatim}
  1084. > a = [3,4,1;0,2,2;0,0,7;zeros(2,3)];
  1085. > b = [14;10;21;6;2];
  1086. \end{verbatim}
  1087.  
  1088.    You've just read that the \RLaB\ operator `\verb+\+' solves systems
  1089.    of equations, so you try it out: 
  1090.  
  1091. \begin{verbatim}
  1092. > x = a \ b
  1093.  x =
  1094.         1  
  1095.         2  
  1096.         3  
  1097. \end{verbatim}
  1098.  
  1099.   You check the answer (note that this is a contrived problem):
  1100.  
  1101. \begin{verbatim}
  1102. > b - a*x
  1103. -7.11e-15  
  1104. -1.78e-15  
  1105. -1.42e-14  
  1106.         6  
  1107.         2  
  1108. \end{verbatim}
  1109.  
  1110.    and it looks ``OK''. The residual in the first three rows is near
  1111.    the machine-epsilon\footnote{Machine-epsilon is the smallest number
  1112.    that your computer can distinguish. A common way to determine
  1113.    machine-epsilon is to divide a variable ({\tt eps})
  1114.    by two until {\tt 1.0 + eps  == 1.0}.}.
  1115.    Now you wish to follow the example in the
  1116.    text more closely, in an attempt to reinforce your reading. The
  1117.    text has stated that the ``normal equations'' are: 
  1118.    $(A^{T}A)x = (A^{T}b)$.
  1119.  
  1120.    Not having read the chapter on Gaussian elimination, and matrix
  1121.    inverses yet you try: 
  1122.  
  1123. \begin{verbatim}
  1124. > x = inv (a'*a) * (a'*b)
  1125.  x =
  1126.         1  
  1127.         2  
  1128.         3  
  1129. \end{verbatim}
  1130.  
  1131.    Fortunately, the problem we are working with is not
  1132.    ill-conditioned, otherwise we may have produced a terrible result
  1133.    with the above procedure. If you want to pursue the reasoning
  1134.    behind the previous statement I suggest you read the section
  1135.    ``Linear Systems of Equations''.
  1136.  
  1137.    Well, this is all too easy, now you want to get dirty, so you move
  1138.    on to orthogonal transformations. You have read about the
  1139.    construction of Householder vectors and reflections; now you would
  1140.    like to try it first-hand. You know that:
  1141.  
  1142.    \[ P = I - 2(vv^{T})/(v^{T}v) \]
  1143.  
  1144.    Where $v$ is the Householder vector used to form the reflection
  1145.    matrix. First you must construct the vector. Your
  1146.    text\footnote{Mine in this case is Golub and VanLoan, ``Matrix
  1147.    Computations''.} tells you that a good method for constructing the
  1148.    Householder vector is:
  1149.  
  1150.   \[ v[2:n] = x[2:n] / (x[1] + sign(x[1]) * \|x\|_{2}) \]
  1151.   \[ v[1] = 1 \]
  1152.  
  1153. \begin{verbatim}
  1154. > a = rand(5,2);               // Start out with a more difficult [A]
  1155. > a
  1156.  a =
  1157.     0.655      0.265  
  1158.     0.129        0.7  
  1159.      0.91       0.95  
  1160.     0.112     0.0918  
  1161.     0.299      0.902  
  1162. > ac1 = a[;1];                 // grab the 1st column of [a] to work with
  1163. > u = norm (ac1, "2");         // compute the 2-norm of [ac1]
  1164. > v[2:5] = ac1[2:5] / (ac1[1] + sign (ac1[1])*u)
  1165.  v =
  1166.         0     0.0705      0.498     0.0611      0.164  
  1167. > v[1] = 1;
  1168. > v = v';                      // make v a column vector
  1169. \end{verbatim}
  1170.  
  1171.    By using the matrix creation, and element referencing features you
  1172.    have generated the vector in 4 commands. We could have used
  1173.    a signal command 
  1174.  
  1175. \begin{verbatim}
  1176. > v = [ 1 , a[;1][2:5]' / (a[1;1] + sign(a[1;1])*norm(a[;1],"2")) ]'
  1177. \end{verbatim}
  1178.  
  1179.    But, this is less than clear. Note that in this case, since we are
  1180.    working with vectors, we only use a single index when subscripting
  1181.    the variables.
  1182.  
  1183.    Now that we have our Householder vector, we are ready to assemble
  1184.    the Householder reflection (matrix).
  1185.  
  1186. \begin{verbatim}
  1187. > P = eye (5,5) - 2*(v*v')/(v'*v)
  1188.  P =
  1189.    -0.558      -0.11     -0.776    -0.0952     -0.255  
  1190.     -0.11      0.992    -0.0547   -0.00671     -0.018  
  1191.    -0.776    -0.0547      0.614    -0.0474     -0.127  
  1192.   -0.0952   -0.00671    -0.0474      0.994    -0.0156  
  1193.    -0.255     -0.018     -0.127    -0.0156      0.958  
  1194. > P*a
  1195.     -1.17       -1.2  
  1196. -1.65e-17      0.596  
  1197. -1.54e-16       0.22  
  1198. -1.31e-17    0.00217  
  1199. -5.39e-17      0.662  
  1200. \end{verbatim}
  1201.  
  1202.    As you can see it worked out just like they said it would. All the
  1203.    elements of the first column of $A$, below the diagonal, have been
  1204.    zeroed out\footnote{Although the numbers are not identically zero,
  1205.    they are on the order of machine precision, and can be considered
  1206.    to be zero. Some programs use fixed-point precision when printing.
  1207.    Although this makes their output look more accurate, it is
  1208.    not.}. In this manner we can proceed to transform $A$ into an upper
  1209.    triangular matrix.
  1210.  
  1211. \clearpage
  1212.  
  1213. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1214.  
  1215. \section{Program Flow Control}
  1216.  
  1217.    We must now take a small diversion before proceeding on with the
  1218.    rest of the objects and discuss flow-control. The flow-control
  1219.    statements available in \RLaB\ are the {\em if-statement}, the {\em
  1220.    while-statement}, the {\em for-statement}, the {\em break-statement}
  1221.    and the {\em continue-statement}.
  1222.  
  1223.    The flow-control statements use a syntax that is {\em similar} to
  1224.    the C-language\footnote{Note we said similar, not identical.}.
  1225.    Braces `\verb+{+' and `\verb+}+' are {\em required} in all of the
  1226.    flow-control statements.
  1227.  
  1228. \subsection{If-Statement}
  1229.  
  1230.    The {\em if-statement} performs a test on the expression in
  1231.    parenthesis, and executes the statements enclosed within braces if
  1232.    the expression is true. The expression must evaluate to a
  1233.    scalar-expression. If the expression evaluates to a vector or
  1234.    matrix a run-time error will result.
  1235.  
  1236.    \begin{tabbing}
  1237.     123456 \= 1234 \=  \kill
  1238.     \> if \ (\  {\it expression} \ )  \nopagebreak \\
  1239.     \> \{               \\
  1240.     \> \> {\it statements}    \\
  1241.     \> \}               \\
  1242.    \end{tabbing}
  1243.  
  1244. \begin{verbatim}
  1245. > if ( 1 ) { "TRUE" }
  1246. TRUE
  1247. > if ( 0 ) { "TRUE" }
  1248. \end{verbatim}
  1249.  
  1250.    An optional `\verb+else+' keyword is allowed to delineate statements
  1251.    that will be executed if the expression tests false:
  1252.  
  1253. \begin{verbatim}
  1254. > if ( 0 ) { "TRUE" else "FALSE" }
  1255. FALSE
  1256. \end{verbatim}
  1257.  
  1258.    The \verb+any+ and \verb+all+ functions are useful with {\em
  1259.    if-statements}. If we want to execute some statements, conditional
  1260.    on the contents of a matrix:
  1261.  
  1262. \begin{verbatim}
  1263. > a=[1,2;3,0];
  1264. > if (!all (all (a))) { "a has a zero element" }
  1265. a has a zero element
  1266. \end{verbatim}
  1267.  
  1268. \subsection{While-Statement}
  1269.  
  1270.    The {\em while-statement} tests the expression in parenthesis, and
  1271.    executes the statements enclosed within braces until the expression
  1272.    is false. The expression must evaluate to a scalar-expression. If
  1273.    the expression evaluates to a vector or matrix a run-time error
  1274.    will result.
  1275.  
  1276.  
  1277.    \begin{tabbing}
  1278.     123456 \= 1234 \=  \kill
  1279.  
  1280.     \> while \ (\  {\it expression} \ ) \\
  1281.     \> \{               \\
  1282.     \> \> {\it statements}    \\
  1283.     \> \}               \\
  1284.    \end{tabbing}
  1285.  
  1286. \begin{verbatim}
  1287. > while ( 0 ) { "TRUE" }
  1288. > i = 0;
  1289. > while ( i < 2 ) { i = i + 1 }
  1290.  i =
  1291.         1
  1292.  i =
  1293.         2
  1294. \end{verbatim}
  1295.  
  1296. \subsection{For-Statement}
  1297.  
  1298.    The {\em for-statement} executes the statements enclosed in braces
  1299.    $N$ times, where $N$ is the number of values in {\it
  1300.    vector-expression}. Each time the statements are executed {\it
  1301.    variable} is set to the $k^{th}$ value of {\it vector-expression},
  1302.    where $k = 1 \ldots\ N$.
  1303.  
  1304.    \begin{tabbing}
  1305.     123456 \= 1234 \=  \kill
  1306.  
  1307.     \> for \ (\  {\it variable} in {\it vector-expression} \ ) \\
  1308.     \> \{               \\
  1309.     \> \> {\it statements}    \\
  1310.     \> \}               \\
  1311.    \end{tabbing}
  1312.  
  1313. \begin{verbatim}
  1314. > for ( i in 1:3 ) { i }
  1315.  i =
  1316.         1
  1317.  i =
  1318.         2
  1319.  i =
  1320.         3
  1321. \end{verbatim}
  1322.  
  1323.    {\it vector-expression} can be any type of vector: real, complex,
  1324.    and string vectors are all acceptable.
  1325.  
  1326. \subsection{Break and Continue Statements}
  1327.  
  1328.    The {\em break} and {\em continue} statements are simply keywords.
  1329.    Usage of {\em break} and {\em continue} is only allowed within {\em
  1330.    while-statements} or {\em for-statements}. {\em break} will cause
  1331.    execution of the current loop to terminate. {\em continue} will
  1332.    cause the next iteration of the current loop to begin.
  1333.  
  1334. \begin{verbatim}
  1335. > for ( i in 1:100 ) { if (i == 3) { break } } i
  1336.  i =
  1337.         3
  1338. > for ( i in 1:4 ) { if (i == 2) { continue } i }
  1339.  i =
  1340.         1
  1341.  i =
  1342.         3
  1343.  i =
  1344.         4
  1345. \end{verbatim}
  1346.  
  1347.    Although they will not be explicitly discussed - there are more
  1348.    examples of flow-control statement usage throughout the remainder
  1349.    of the primer.
  1350.    
  1351. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1352.  
  1353. \section{Objects---Program Functions}    \label{sect-functions}
  1354.  
  1355.    Like matrices and strings, functions are stored as ordinary
  1356.    variables in the symbol table. Function's treatment as variables
  1357.    explains the somewhat peculiar syntax required to create and store
  1358.    a function.
  1359.  
  1360. \begin{verbatim}
  1361. > logsin = function ( x ) { return log (x) .* sin (x) }
  1362.     <user-function>
  1363. \end{verbatim}
  1364.  
  1365.    The above statement creates a function, and assigns it to the
  1366.    variable \verb+logsin+. The function can then be used like:
  1367.  
  1368. \begin{verbatim}
  1369. > logsin ( 2 )
  1370.      0.63
  1371. \end{verbatim}
  1372.  
  1373.    Like variables, function can be copied, re-assigned, and destroyed. 
  1374.  
  1375. \begin{verbatim}
  1376. > y = logsin
  1377.     <user-function>
  1378. > y (2)
  1379.      0.63
  1380. > // Overwrite it with a matrix
  1381. > logsin = rand (2,2);
  1382. > // Check that y is still a function
  1383. > y (3)
  1384.     0.155
  1385. \end{verbatim}
  1386.  
  1387.    If you try re-assigning a built-in function you will get a run-time
  1388.    error message. The built-in functions, those that are programmed in
  1389.    C, are a permanent part of the environment. So that users may
  1390.    always rely on their availability, they cannot be re-assigned, or
  1391.    copied. 
  1392.  
  1393.    Variables that represent user-functions can also be part of list
  1394.    objects. Sometimes it can be useful to group functions that serve a
  1395.    similar purpose, or perform different parts of a larger procedure.
  1396.  
  1397. \begin{verbatim}
  1398. list = << logsin = logsin >>
  1399.    logsin       
  1400. > list.logsin (2)
  1401.      0.63
  1402. > list.expsin = function ( x ) { return exp (x) .* sin (x) }
  1403.    expsin       logsin       
  1404. > list.expsin (2)
  1405.      6.72
  1406. \end{verbatim}
  1407.  
  1408. \subsection{Function Syntax}
  1409.  
  1410.    The function syntax is fairly simple. The basic form of a function
  1411.    is:
  1412.  
  1413.    \begin{tabbing}
  1414.     123456 \= 1234 \=  \kill
  1415.  
  1416.     \> function \ (\  {\it argument list} \ ) \\
  1417.     \> \{               \\
  1418.     \> \>               \\
  1419.     \> \> {\it statements}    \\
  1420.     \> \>               \\
  1421.     \> \}               \\
  1422.    \end{tabbing}
  1423.  
  1424.    If a syntax error is encountered while the function is being
  1425.    entered (read), definition of the function must begin again from
  1426.    the very beginning.
  1427.  
  1428.    There are several statements that only make sense within functions:
  1429.  
  1430.    \begin{tabbing}
  1431.     123456 \= 1234 \=  \kill
  1432.     \> global \ (\  {\it global-var-1, global-var-2 \ldots} \ ) \\
  1433.  
  1434.     \> local \ (\  {\it local-var-1, local-var-2 \ldots} \ ) \\
  1435.  
  1436.     \> return {\it expression} \\
  1437.  
  1438.    \end{tabbing}
  1439.  
  1440.  
  1441.    The \verb+global+ and \verb+local+ statements are optional. There
  1442.    are no restrictions on the number of \verb+local+ or \verb+global+
  1443.    statements or where they occur in the function. However, since
  1444.    these two statements only affect variables that are used {\em
  1445.    after} the declaration, it is recommended that you use \verb+local+
  1446.    and \verb+global+ at the {\em beginning} of each function.
  1447.  
  1448.    The \verb+return+ statement is also optional. There are no
  1449.    restrictions on the number of return statements, or their
  1450.    placement. A function can return from any point in its
  1451.    execution. The return statement must return a value. The value can
  1452.    be any \RLaB\ object.
  1453.  
  1454. \subsection{Function Scoping Rules}
  1455.  
  1456.    When you start a \rlab\ session, either interactively or in
  1457.    batch-mode, you create an environment. The environment or workspace
  1458.    consists of the built-in functions, and any other variables or
  1459.    functions you may have added. The workspace will also be referred
  1460.    to as the global-symbol-table or the global scope.
  1461.  
  1462.    There are two other types of environment available: a function's
  1463.    local environment and a file's static environment\footnote{We will
  1464.    use the term environment and scope interchangeably.}
  1465.  
  1466.    A function's local scope is temporary, it is created when the
  1467.    function is invoked, and is destroyed when the function returns. A
  1468.    file's static scope is created when the file is loaded, and remains
  1469.    intact until the \rlab\ session is terminated.
  1470.  
  1471.    The different scopes serve to protect data from operations that
  1472.    occur in the other scopes. There is some degree of overlap in order
  1473.    to allow flexibility. Functions can affect file-static and global
  1474.    scopes; statements within files can affect statements within other
  1475.    files and the global scope. More simply put, the "lower" scopes
  1476.    generally have access to the "higher" scopes. When a variable is
  1477.    used, \rlab\ uses certain rules to "bind" the variable. When we use
  1478.    the term bind or bound, we mean that the variable name is
  1479.    associated with an entry in one of the three types of symbol
  1480.    tables.
  1481.  
  1482.  
  1483.    \begin{description}
  1484.  
  1485.    \item[File-Scope:] Variables that are in a file (but not within a
  1486.     function) are bound to the global-symbol-table (global-scope
  1487.     or global-environment) unless a static declaration is
  1488.     used. When a variable is declared static it is bound to the
  1489.     file's symbol table. From that point on, the variable will
  1490.     remain bound to the file's scope. When a variable is declared
  1491.     static, it is not visible from the global environment or from
  1492.     any other files.
  1493.  
  1494.    \item[Function Local Scope:] In general, variables used within a
  1495.     function (other than the function's arguments) are bound to
  1496.     the function's local scope (there are ways to override this
  1497.     behavior). Variables bound to a function's local scope are not
  1498.     visible from a file's scope or from the global scope. They are
  1499.     created (undefined) when the function is invoked, and
  1500.     destroyed when the function returns.
  1501.  
  1502.         There are exceptions: variables used in a function context are
  1503.     bound to the global-symbol-table. For example:
  1504.  
  1505. \begin{verbatim}
  1506.             x = a * sin ( pi )
  1507. \end{verbatim}
  1508.  
  1509.     \verb+sin+ is used in a function context, and is bound to the
  1510.     global scope, while \verb+x+, \verb+a+, and \verb+pi+ are
  1511.     bound to the function's local environment.
  1512.  
  1513.     Function's that are defined within a file have full access to
  1514.     the file's static variables.  Function variables will be bound
  1515.     to the file's scope before local binding occurs.
  1516.  
  1517. \begin{verbatim}
  1518.         ---- beginning of file.r ----
  1519.  
  1520.         static (A, pi)
  1521.         pi = atan(1)*4;
  1522.  
  1523.         fun = function ( a ) { return A*sin(pi*A*a); }
  1524.  
  1525.         ---- end of file.r ----
  1526. \end{verbatim}
  1527.  
  1528.     When `fun' is created it binds `A' and `pi' to file.r's static
  1529.     environment.
  1530.  
  1531.     There are two declarations: `global' and `local' that can be
  1532.     used to override the default behavior if necessary. Variables
  1533.     declared local will be bound to the function's local scope,
  1534.     and variable declared global will be bound to the global
  1535.     scope.
  1536.  
  1537. \end{description}
  1538.  
  1539. \subsection{Function Argument Passing}
  1540.  
  1541.    Arguments can be passed by reference, or value. The default
  1542.    behavior is to pass by reference. Pass by references indicates that
  1543.    the variables used in the function call are directly referenced
  1544.    from within the function. Pass by value means that only the value
  1545.    of the argument is passed to the function. In other words, the
  1546.    arguments are copied. In order to pass a function argument by
  1547.    value, the user needs to declare that function argument as
  1548.    local. This method allows users to selectively determine how to
  1549.    pass each function argument.
  1550.  
  1551.    A function can be called with fewer arguments than specified in the
  1552.    definition; this is called a ``short-list''. When this situation
  1553.    occurs, \rlab\ pads the argument list with extra undefined
  1554.    variables. Arguments can be ``skipped'' when calling a
  1555.    function. The ``skipped'' arguments are passed to the function as
  1556.    undefined variables. To ``skip'' an argument just leave it out of
  1557.    the argument list, but don't forget the commas:
  1558.  
  1559. \begin{verbatim}
  1560. > x = function ( a, b, c, d ) { a ? b ? c ? d ? }
  1561.     <user-function>
  1562. > x (1);    // short-list
  1563.         1
  1564.     UNDEFINED
  1565.     UNDEFINED
  1566.     UNDEFINED
  1567. > x(1,,2);    // skipped arguments
  1568.         1
  1569.     UNDEFINED
  1570.         2
  1571.     UNDEFINED
  1572. \end{verbatim}
  1573.  
  1574.    As far as \RLaB\ is concerned undefined variables do not exist. The
  1575.    function \verb+exist+ will return true (1) if its argument exists,
  1576.    and false (0) if its argument is undefined.
  1577.  
  1578.    A function cannot be called with more arguments than specified in
  1579.    the function definition. If you attempt to do so, a run-time error
  1580.    will result.
  1581.  
  1582.    Function argument classes and class-types are not specified during
  1583.    definition. When writing ``robust'' functions the author should
  1584.    take some care to check that the function argument(s) are of the
  1585.    correct class and type, if necessary.  The documentation (comments)
  1586.    should clearly define the requisite argument types and the function
  1587.    return object. If the function documentation does not clearly state
  1588.    that the arguments will be modified during function execution, care
  1589.    should be exercised to avoid changing any of the function
  1590.    arguments. If necessary, the function arguments can be passed by
  1591.    value so that changes will not affect the caller's variables.
  1592.  
  1593.    If you wish to write function(s) to serve as often used utilities
  1594.    or libraries, then care should be taken to declare all variables
  1595.    (other than function arguments or built-in functions) as
  1596.    local. Declaring all function variables as local will prevent
  1597.    accidental destruction of user's global variables.
  1598.  
  1599.    \RLaB\ has a special built-in function (\verb+fvscope+) that
  1600.    analyzes user-functions, and makes a report describing which
  1601.    variables are local, arguments, global, or
  1602.    file-static. \verb+fvscope+ can be very helpful when writing your
  1603.    first function(s) to help you understand how \RLaB\ resolves
  1604.    variable references.
  1605.  
  1606. \subsection{Function Recursion}
  1607.  
  1608.    Functions can call themselves recursively. Each time execution
  1609.    passes into the function the local variables are (re)created. There
  1610.    is a special keyword: \verb+$self+, which must be used to force a
  1611.    function to refer to itself. 
  1612.  
  1613. \begin{verbatim}
  1614. fac = function ( a ) 
  1615. {
  1616.   if(a <= 1) 
  1617.   {
  1618.       return 1;
  1619.   else
  1620.       return a*$self (a-1);
  1621.   }
  1622. };
  1623. \end{verbatim}
  1624.  
  1625.    In the previous example a factorial computation is performed using
  1626.    recursion\footnote{Not necessarily an efficient way to compute the
  1627.    factorial.}. In the second return statement, the function calls
  1628.    itself until $a \leq 1$. 
  1629.  
  1630. \subsection{Files}
  1631.  
  1632.    Simple ``one-liner'' functions can be typed in at the command line.
  1633.    However, they are destroyed when the \RLaB\ session is ended. Most
  1634.    users will want to create their functions in a text-editor as
  1635.    ordinary ASCII files.
  1636.  
  1637.    The function \verb+load+ will execute the \rlab\ statements in a
  1638.    file as if they were typed at the command line. The \rlab\ command
  1639.    \verb+rfile+ searches a specified path for files with a `.r'
  1640.    extension. When the \verb+rfile+ command finds a file that matches
  1641.    its argument, it executes the \rlab\ statements in the file as if
  1642.    they were typed at the command line.
  1643.  
  1644.    Statements in a file are executed in the same manner as they would
  1645.    be had they been typed in interactively. Files containing ordinary
  1646.    commands and multiple functions are acceptable. In fact, complete
  1647.    programs can be written and run interactively or in batch mode. To
  1648.    run a program in batch mode you can try:
  1649.  
  1650. \begin{verbatim}
  1651. % rlab program.r &
  1652. \end{verbatim}
  1653.  
  1654.    Or the program could contain \verb+#!/usr/local/bin/rlab+ on the
  1655.    first line. Then, if your operating system provides the proper
  1656.    support, \rlab\ can execute your program, interactively, or in the
  1657.    background by simply typing:
  1658.  
  1659. \begin{verbatim}
  1660. $ chmod +x program.r
  1661. $ ./program.r
  1662. \end{verbatim}
  1663.  
  1664. \subsection{Example} \label{sect-func-example}
  1665.  
  1666.    Many functions are included with the \RLaB\ source distribution.
  1667.    Functions can be found in the distribution subdirectories
  1668.    \verb+./rlib+, \verb+./toolbox+, and \verb+./examples+. These 
  1669.    directories are normally installed under \verb|/usr/local/lib/rlab|.
  1670.    
  1671.    We will continue with some simple examples demonstrating
  1672.    function creation and usage. We will carry on with the exercise of
  1673.    learning least-squares techniques.
  1674.  
  1675.    In some earlier examples we played with solving a set of normal
  1676.    equations, and tried a simple experiment with Householder
  1677.    reflections. Now we want to try out this technique, and decompose a
  1678.    matrix into two matrices: $Q$ and $R$; such that $A =
  1679.    QR$.\footnote{For an excellent discussion of the $QR$ decomposition
  1680.    please refer to ``Matrix Computations'' Golub and Van Loan.}
  1681.  
  1682.    We are going to decompose an entire matrix, so we will want to
  1683.    automate the procedures we used in previous examples. The first was
  1684.    creating a Householder vector. Instead of typing in our function at
  1685.    the command-line, we will use a text-editor to create the function
  1686.    in a file so that we can correct our mistakes without retyping the
  1687.    entire function.
  1688.  
  1689. \begin{verbatim}
  1690. //
  1691. // house_v(): Given an N-vector V, generate an n-vector V
  1692. // with V[1] = 1, such that (eye(n,n) - 2*(V*V')/(V'*V))*X
  1693. // is zero in all but the 1st component.
  1694. //
  1695.  
  1696. static (sign)
  1697.  
  1698. house_v = function(v)
  1699. {
  1700.   local(v)
  1701.   
  1702.   n = max( size(v) );
  1703.   u = norm(v, "2");
  1704.   if(u != 0)
  1705.   {
  1706.     b = v[1] + sign(v[1])*u;
  1707.     if(n > 1) 
  1708.     {
  1709.       v[2:n] = v[2:n]/b;
  1710.     }
  1711.   }
  1712.   v[1] = 1;
  1713.   return v;
  1714. };
  1715.  
  1716. sign = function ( X )
  1717. {
  1718.   if (X >= 0) { return 1; else return -1; }
  1719. }
  1720. \end{verbatim}
  1721.  
  1722.    Note that our new function is more complicated than our earlier
  1723.    ``one-liner''. This is due to the fact that the function is more
  1724.    efficient, and does some input-checking. Notice that the variables
  1725.    \verb+b+, \verb+n+, \verb+u+, and \verb+v+ are {\em local}; these
  1726.    local variables will never be seen by the user, and will not
  1727.    interfere with any pre-existing variables by the same name in the
  1728.    global-workspace.
  1729.  
  1730.    Also note that the function argument, \verb+v+ is copied to the
  1731.    function local variable \verb+v+. This prevents the function from
  1732.    changing the values in the input argument, and thus destroying the
  1733.    contents of the caller's variable.
  1734.  
  1735.    One other important feature of the new function is the usage of
  1736.    the \verb+sign+ function. \verb+house_v+ requires that the sign
  1737.    function return either $1$ or $-1$. The \RLaB\ built-in \verb+sign+
  1738.    function will return zero when its argument is zero; this
  1739.    behavior is unacceptable, so we have written our own sign
  1740.    function. Declaring our new sign function to be static means that
  1741.    it will only affect statements within the file \verb+house_v.r+.
  1742.  
  1743.    To use our new function type:
  1744.  
  1745. \begin{verbatim}
  1746. > a = rand (4,2);
  1747. > x = house_v (a[;1])
  1748.  x =
  1749.         1  
  1750.     0.434  
  1751.     0.042  
  1752.     0.412  
  1753. \end{verbatim}
  1754.  
  1755.    Now that we can generate a Householder vector, we need to
  1756.    automatically form the Householder reflection, and use it to reduce
  1757.    $A$ to upper triangular form.
  1758.  
  1759. \begin{verbatim}
  1760. // P.r
  1761. // P: Generate P matrix
  1762.  
  1763. P = function ( V )
  1764. {
  1765.   m = max( size(V) );
  1766.   return [ eye(m,m) - 2*(V*V')./(V'*V) ];
  1767. };
  1768. \end{verbatim}
  1769.  
  1770.    This function is a small one, and simply implements the formula we
  1771.    demonstrated earlier. We can test out our two new functions like so:
  1772.  
  1773. \begin{verbatim}
  1774. > ( p1 = P (house_v (a[;1])) ) * a
  1775.     -1.49      -1.11  
  1776. -4.09e-17     0.0174  
  1777. -2.87e-18      0.354  
  1778. -8.89e-17     -0.779  
  1779. > p1' * p1
  1780.         1   4.79e-17   2.75e-18    1.8e-17  
  1781.  4.79e-17          1  -4.78e-18  -2.51e-18  
  1782.  2.75e-18  -4.78e-18          1      9e-18  
  1783.   1.8e-17  -2.51e-18      9e-18          1  
  1784. \end{verbatim}
  1785.  
  1786.    Our new function seems to be working as expected. The computed
  1787.    Householder reflection, \verb+p1+, zeros out all of the elements
  1788.    below the first in column one of \verb+a+. Additionally \verb+p1+
  1789.    is an orthogonal transformation, as demonstrated by computing
  1790.    ${P_{1}}^{T}P_{1}$. It is usually more efficient to build up
  1791.    programs as a collection of simple functions, like we are doing
  1792.    here, testing each as it is written, and making the appropriate
  1793.    fixes.
  1794.  
  1795.    Function debugging can be easily accomplished by simply removing key
  1796.    `\verb+;+' to turn expression printing on. Additionally, one can
  1797.    comment out \verb+local+ statements so that a function's variables
  1798.    can be examined after function execution.
  1799.  
  1800.    Now there are two more pieces, a better implementation of \verb+P+
  1801.    called \verb+house_row+\footnote{See ``Matrix Computations'' by
  1802.    Golub and VanLoan.}, and the final function (\verb+house_qr+) that
  1803.    will apply the transformations in sequence to $A$ to produce the
  1804.    upper-triangular $R$, and the orthogonal $Q$.
  1805.  
  1806. \begin{verbatim}
  1807. //
  1808. // house_row(): Given an MxN matrix A and a non-zero M-vector V
  1809. // with V[1] = 1, the following algorithm overwrites A with 
  1810. // P*A, where P = eye(m,m) - 2*(V*V')/(V'*V)
  1811. //
  1812.  
  1813. house_row = function(A, v)
  1814. {
  1815.   local(A)
  1816.   
  1817.   b = -2/(v'*v);
  1818.   w = b*A'*v;
  1819.   A = A + v*w';
  1820.   return A;
  1821. };
  1822. \end{verbatim}
  1823.  
  1824.  
  1825. \begin{verbatim}
  1826. // house_qr.r
  1827. // Given A, with M >= N, the following function finds Householder
  1828. // matrices H1,...Hn, such that if Q = H1*...Hn, then Q'*A = R is
  1829. // upper triangular.
  1830.  
  1831. // House.qr returns a list containing `q', and `r'
  1832.  
  1833. rfile house_row
  1834. rfile house_v
  1835. rfile P
  1836.  
  1837. house_qr = function ( A )
  1838. {
  1839.   local (A)
  1840.   
  1841.   m = A.nr; n = A.nc;
  1842.   v = zeros(m,1);
  1843.   q = eye (m, m);
  1844.  
  1845.   for(j in 1:n)
  1846.   {
  1847.     // Generate the Householder vector
  1848.     v[j:m] = house_v( A[j:m;j] );
  1849.  
  1850.     // Apply the Householder reflector to A
  1851.     A[j:m;j:n] = house_row( A[j:m;j:n], v[j:m] );
  1852.  
  1853.     // Create Q
  1854.     if(j < m) 
  1855.     {
  1856.       q = P ([ zeros (j-1,1); 1; v[j+1:m] ]) * q;
  1857.     }
  1858.   }
  1859.   return << q = q'; r = A >>;
  1860. };
  1861. \end{verbatim}
  1862.  
  1863.    Notice the three \verb+rfile+ statements near the top of the file.
  1864.    These statements ensure that the user-function dependencies are
  1865.    resolved {\em before} we try and execute the function. Also note
  1866.    how \verb+house_qr+ returns two matrices in a list, with element
  1867.    names \verb+q+, and \verb+r+. We can use, and test, this new
  1868.    function like:
  1869.  
  1870. \begin{verbatim}
  1871. > x = house_qr ( a )
  1872.    q            r            
  1873. > x.q * x.r
  1874.       0.7       0.96  
  1875.      0.95      0.915  
  1876.    0.0918      0.441  
  1877.     0.902     0.0735  
  1878. > a
  1879.  a =
  1880.       0.7       0.96  
  1881.      0.95      0.915  
  1882.    0.0918      0.441  
  1883.     0.902     0.0735  
  1884. \end{verbatim}
  1885.  
  1886.    A visual comparison shows that our function does indeed work. 
  1887.    Now we wish to use this factorization to compute a solution to our
  1888.    original least-squares problem. Since we have decomposed $A$ into
  1889.    two matrices, one of which is upper triangular, we can reformulate
  1890.    the problem as a simple back-substitution. The \RLaB\ built-in
  1891.    function \verb+solve+ will do this for us, since \verb+sr+ is
  1892.    already upper-triangular, all \verb+solve+ will do is the
  1893.    back-substitution.
  1894.  
  1895. \begin{verbatim}
  1896. > a = [3,4,1;0,2,2;0,0,7;zeros(2,3)];
  1897. > b = [14;10;21;6;2];
  1898. > x = house_qr (a);
  1899. > sq = x.q[;1:3];
  1900. > sr = x.r[1:3;];
  1901. > z = b'*sq;
  1902. > sol = solve (sr, z')
  1903.  sol =
  1904.         1  
  1905.         2  
  1906.         3  
  1907. > b - a*sol
  1908.         0  
  1909.         0  
  1910.         0  
  1911.         6  
  1912.         2  
  1913. \end{verbatim}
  1914.  
  1915.    Now that we have built our own \verb+qr()+ I should tell you that
  1916.    \RLaB\ has  a built-in \verb+qr()+ that is much more robust, and
  1917.    significantly faster.
  1918.  
  1919. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1920.  
  1921. \section{Objects---Other Data Structures}
  1922.  
  1923.    Although \RLaB\ is primarily a linear-algebra programming tool,
  1924.    other data structures are necessary to allow the user some
  1925.    flexibility, and a little extensibility. The two remaining data
  1926.    structures do just that. Strings allow users/programmers to write
  1927.    intelligible error messages, and properly annotate program inputs
  1928.    and outputs, as well as label quantities during program execution.
  1929.    The list object is a very flexible data structure that can hold
  1930.    numeric, string, function and other list objects. Since lists are
  1931.    indexed in an associative fashion, they are a very powerful tool.
  1932.  
  1933. \subsection{Strings}
  1934.  
  1935.    When performing numeric computations, strings are not normally used
  1936.    for much except error messages and such. However, there are many
  1937.    other tasks for which strings are quite useful. 
  1938.  
  1939.    String objects can be treated in a manner similar to numeric
  1940.    objects, with the main difference being the different string
  1941.    operators. The only numeric operator that works on strings is the
  1942.    `\verb-+-' which catenates the left and right string operands
  1943.    together.
  1944.  
  1945. \begin{verbatim}
  1946. > "first part of the string " + "and the second part of the string"
  1947. first part of the string and the second part of the string
  1948. \end{verbatim}
  1949.  
  1950.    The other numeric operators will only produce a runtime error
  1951.    message when used with strings.
  1952.  
  1953. \begin{verbatim}
  1954. > "string1" * "string2"
  1955. rlab: NULL, NULL, 1st arg invalid for multiply
  1956. \end{verbatim}
  1957.  
  1958.    The relational and logical operator do work with string objects.
  1959.    For instance, you can compare two strings:
  1960.  
  1961. \begin{verbatim}
  1962. > "string-a" == "string-b"
  1963.         0
  1964. \end{verbatim}
  1965.  
  1966.    Or two string matrices:
  1967.  
  1968. \begin{verbatim}
  1969. > ["el-1", "el-2"] == ["el-1", "el-x"]
  1970.         1          0  
  1971. \end{verbatim}
  1972.  
  1973.    Functions exist to aid with string to number conversions
  1974.    (\verb+num2str+), and reading strings from the standard input
  1975.    (\verb+input+).
  1976.  
  1977. \begin{verbatim}
  1978. > x = input ("input a string > ", "s")
  1979. input a string > teststring
  1980. teststring
  1981. \end{verbatim}
  1982.  
  1983.    The function \verb+strsplt+ will split an arbitrary string into a
  1984.    matrix of one-character strings. This allows the user to operate on
  1985.    individual characters in a string; the `\verb-+-' operator can be
  1986.    used to ``glue'' the desired pieces back together again.
  1987.  
  1988. \begin{verbatim}
  1989. > x = "this is a single string";
  1990. > strsplt (x)
  1991. t  h  i  s     i  s     a     s  i  n  g  l  e     s  t  r  i  n  g  
  1992. \end{verbatim}
  1993.    
  1994.    We will do a little more with strings in Section~\ref{sect-lists}.
  1995.  
  1996. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  1997.  
  1998. \subsection{Lists}    \label{sect-lists}
  1999.  
  2000.    A list is a heterogeneous associative array. Simply, a list is an
  2001.    array whose elements can be from different classes. Thus a list can
  2002.    contain numeric, string, function, and other list objects. Lists
  2003.    have many uses, only some of which we will demonstrate herein.
  2004.  
  2005.    To create a list-object use the `\verb+<<+' and `\verb+>>'+'
  2006.    operators. The list will be created, and the objects inside the
  2007.    `\verb+<< >>+' will be copied into the new list. If the objects are
  2008.    not renamed during the list-creation, they will be given numerical
  2009.    index values.
  2010.  
  2011. \begin{verbatim}
  2012. > a = rand(3,4); b = sqrt (a); c = 2*a + b;
  2013. > ll = << a ; b ; c >>
  2014.    1            2            3            
  2015. > ll2 = << A = a; b = b ; x = c >>
  2016.    A            b            x            
  2017. > ll2.A == ll.[1]
  2018.         1          1          1          1  
  2019.         1          1          1          1  
  2020.         1          1          1          1  
  2021. \end{verbatim}
  2022.  
  2023.    Lists are not indexed in what is perceived as the ``traditional
  2024.    manner''. Instead the list index is converted to a string, and the
  2025.    string value is used to look-up the referenced
  2026.    object\footnote{\RLaB\ lists are similar to AWK associative
  2027.    arrays.}. There are two methods for referencing the elements of a
  2028.    list, the first, a shorthand notation looks like:
  2029.  
  2030.    \begin{quote}
  2031.       list\_name . element\_name
  2032.    \end{quote}
  2033.  
  2034.    In this case, the {\em list\_name} and {\em element\_name} must
  2035.    follow the same rules as ordinary variable names. The second
  2036.    method for indexing a list is:
  2037.  
  2038.    \begin{quote}
  2039.       list\_name . \verb+[+ numeric\_or\_string\_expression \verb+]+
  2040.    \end{quote}
  2041.  
  2042.    The second method allows string and numeric variables to be
  2043.    evaluated before doing the conversion to string type\footnote{If one
  2044.    is necessary.}. 
  2045.  
  2046.    As you have seen in an earlier example lists can be used within
  2047.    functions when it is necessary to return several values. Because of
  2048.    the lists flexible nature a function can return matrices of
  2049.    differing sizes and types, as well as strings, other lists, or
  2050.    user-functions. 
  2051.  
  2052. \subsubsection{Examples}
  2053.  
  2054.    The \verb+getline+ function reads from a designated file, or pipe,
  2055.    and separates the input into whitespace separated tokens. The
  2056.    tokens are either numbers or strings. In this example we will use
  2057.    the \verb+getline+ function, and \RLaB\ piping capability to read
  2058.    the output from the UNIX ps command, and sum the numbers in the 5th
  2059.    column (the resident process size). 
  2060.  
  2061. \begin{verbatim}
  2062. > psize = 0;
  2063. > while (length (ans = getline ("|/usr/ucb/ps -aux | grep ian")))
  2064.   {
  2065.     psize = psize + ans.[5];
  2066.   }
  2067. > close ("|/usr/ucb/ps -aux | grep ian");
  2068. > psize
  2069.  psize =
  2070.  2.26e+03
  2071. \end{verbatim}
  2072.  
  2073.    The following simple example makes extensive use of the list
  2074.    object's capabilities. This example consists of two user-functions
  2075.    that were written to allow someone to index a matrix with strings,
  2076.    or numeric quantities that are not necessarily equal to the integer
  2077.    row and column numbers.
  2078.  
  2079.    Two special qualities of lists are used in this example. The first
  2080.    is the ability to group together related objects; thus the matrix,
  2081.    and its row and column labels are copied into a list-object. The
  2082.    second special quality is the associative nature of the list
  2083.    indices. When constructing the row and column labels, we create two
  2084.    lists that are members of the top-level list. These sub-lists
  2085.    contain the row or column label as the index value, and the integer
  2086.    row or column number as data.
  2087.  
  2088. \begin{verbatim}
  2089. //
  2090. // Create a list-object, a matrix with row and 
  2091. // column labels. Then the matrix can be indexed
  2092. // with the labels by using lb().
  2093. //
  2094.  
  2095. mklb = function (mat, rl, cl)
  2096. {
  2097.   lrl = <<>>; lcl = <<>>;
  2098.   if (!exist (rl))
  2099.   {
  2100.     rl = 1:mat.nr;
  2101.   else
  2102.     if (length (rl) != mat.nr) { error ("mklb: rl wrong size"); }
  2103.   }
  2104.  
  2105.   for (i in 1:rl.n)
  2106.   {
  2107.     lrl.[rl[i]] = i;
  2108.   }
  2109.  
  2110.   if (!exist (cl))
  2111.   {
  2112.     lcl = 1:mat.nc;
  2113.   else
  2114.     if (length (cl) != mat.nc) { error ("mklb: cl wrong size"); }
  2115.   }
  2116.  
  2117.   for (i in 1:cl.n)
  2118.   {
  2119.     lcl.[cl[i]] = i;
  2120.   }
  2121.  
  2122.   return << m = mat; rl = lrl; cl = lcl >>
  2123. };
  2124. \end{verbatim}
  2125.  
  2126.    the function \verb+mklb+ creates a list containing matrix, row,
  2127.    and column labels. Looking closely at the for-loops you will notice
  2128.    that the labels values are actually the index values of the
  2129.    lists \verb+lrl+ and \verb+lcl+. This method is used since it
  2130.    provides extremely easy access to the matrix elements in the next
  2131.    function \verb+lb+.
  2132.  
  2133. \begin{verbatim}
  2134. lb = function ( mlb, rl, cl )
  2135. {
  2136.   // Create row indices
  2137.  
  2138.   if (!exist (rl)) 
  2139.   { 
  2140.     irl = 1:mlb.m.nr;        // use all the rows
  2141.   else
  2142.     for (i in 1:rl.n)
  2143.     {
  2144.       irl[i] = mlb.rl.[rl[i]];
  2145.     }
  2146.   }
  2147.  
  2148.   // Create column indices
  2149.  
  2150.   if (!exist (cl))
  2151.   {
  2152.     icl = 1:mlb.m.nc;        // use all the columns
  2153.   else
  2154.     for (i in 1:cl.n)
  2155.     {
  2156.       icl[i] = mlb.cl.[cl[i]];
  2157.     }
  2158.   }
  2159.  
  2160.   return mlb.m[irl; icl]
  2161. };
  2162. \end{verbatim}
  2163.  
  2164.    The for-loops in \verb+lb+ simply loop through the specified
  2165.    indices, using them as index values to the internal row and column
  2166.    lists. Once the numeric vectors \verb+irl+ and \verb+icl+ have been
  2167.    formed the specified matrix elements are easily returned.
  2168.  
  2169.    To use the new functions you might:
  2170.  
  2171. \begin{verbatim}
  2172. > m = [1,2,3;4,5,6;7,8,9];
  2173. > ml = mklb (m, ["r1","r2","r3"], ["c1","c2","c3"])
  2174.    cl           m            rl           
  2175. > lb (ml, ["r1","r3"])
  2176.         1          2          3  
  2177.         7          8          9  
  2178. > lb (ml, ["r1","r3"], "c1")
  2179.         1  
  2180.         7  
  2181. > lb (ml, , "c2")
  2182.         2  
  2183.         5  
  2184.         8  
  2185. \end{verbatim}
  2186.  
  2187. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2188. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2189.  
  2190. \section{Builtin functions}
  2191.  
  2192.    \RLaB\ comes with many built-in and user-functions. The built-in
  2193.    functions are available any time \rlab\ is run, regardless of the
  2194.    command-line options. The user-functions that are delivered with
  2195.    \RLaB\ may, or may not be accessible, depending upon how \rlab\ has
  2196.    been configured on your computer and the command-line options used.
  2197.  
  2198.    Typing `\verb+rlab -ql+' will run \rlab\ without executing the
  2199.    \verb+.rlab+ file or loading any of the delivered user-functions.
  2200.    The built-in functions in \RLaB\ are unlike user-functions in that
  2201.    users cannot destroy or reassign them to other
  2202.    variables\footnote{The exception to this statement is the use of
  2203.    static variables, which can obscure built-in functions - see the
  2204.    Section~\ref{sect-func-example}.}. This protection is in place
  2205.    so that users will be able to write portable libraries using the
  2206.    built-in functions.
  2207.  
  2208.    \RLaB\ does {\em not} automatically search \verb+RLAB_SEARCH_PATH+
  2209.    for R-files when an unresolved reference is encountered. Instead,
  2210.    the user must explicitly \verb+load+, or use the \verb+rfile+
  2211.    command to get \RLaB\ to load and compile the function or
  2212.    statements. To see what functions are currently available type:
  2213.    `\verb+what()+', this will list all of the currently available
  2214.    functions. Typing `\verb+rfile+' from within \rlab\ will list all
  2215.    of the R-files in the directories listed in the environment
  2216.    variable \verb+RLAB_SEARCH_PATH+. The files displayed by the
  2217.    \verb+rfile+ command can be loaded by typing `\verb+rfile filename+',
  2218.    where \verb+filename+ is the name of the R-file to load,
  2219.    {\em without} the \verb+.r+ extension.
  2220.  
  2221. \subsection{Function Behavior}
  2222.  
  2223.    Many of the delivered functions fall into one of three categories:
  2224.    scalar-functions, vector-functions, or matrix-functions. The list
  2225.    below gives examples from each type of function, but is not
  2226.    all-inclusive. 
  2227.  
  2228.    \begin{description}
  2229.  
  2230.      \item[Scalar Functions:] These functions operate on scalars, and
  2231.            treat matrices in an element-by-element fashion. Some
  2232.            examples are:
  2233.  
  2234.            \begin{tabbing}
  2235.              function1 \= function2 \= function2 \= function4 \kill        
  2236.              abs \> exp \> floor \> round \\
  2237.              cos \> sin \> tan \> ceil \\
  2238.              sqrt \> real \> imag \> conj \\
  2239.              isnan \> int \> \> \\
  2240.            \end{tabbing}
  2241.  
  2242.      \item[Vector Functions:] These functions operate on vectors,
  2243.            either row-vectors (1-by-$n$) or column vectors ($m$-by-1),
  2244.            in the same fashion.  If the argument is a matrix with $m
  2245.            \geq 1$ then the operation is performed in a column-wise
  2246.            fashion. Some examples are:
  2247.  
  2248.            \begin{tabbing}
  2249.              function1 \= function2 \= function2 \= function4 \kill        
  2250.              sum \> cumsum \> prod \> cumprod \\
  2251.              mean \> max \> min \> fft \\
  2252.              sort \> any \> all \> ifft \\
  2253.            \end{tabbing}
  2254.  
  2255.            When using a vector oriented function, like \verb+max()+ it
  2256.            is possible to operate on matrix objects. For example the
  2257.            maximum value in a matrix can be obtained via 
  2258.            \verb+max (max (a))+. The first call to \verb+max()+
  2259.            returns a vector of the maximum values from each column,
  2260.            and the second call to \verb+max()+ returns the maximum
  2261.            value in the matrix.
  2262.  
  2263.      \item[Matrix Functions:] These functions operate on matrices as a
  2264.            single entity. Some examples are:
  2265.  
  2266.            \begin{tabbing}
  2267.              function1 \= function2 \= function2 \= function4 \kill        
  2268.              balance \> chol \> det \> eig \\
  2269.              hess \> inv \> lu \> norm \\
  2270.              pinv \> qr \> rank \> rcond \\
  2271.              reshape \> solve \> svd \> symm \\
  2272.              factor \> backsub \> issymm \\
  2273.            \end{tabbing}
  2274.  
  2275.      \item[Misc. Functions:] These functions are in this particular
  2276.            category simply because they don't fit anywhere else. Some
  2277.            examples are:
  2278.  
  2279.            \begin{tabbing}
  2280.              function1 \= function2 \= function2 \= function4 \kill        
  2281.              system \> getline \> show \> who \\
  2282.              what \> tic \> toc \> printf \\
  2283.              format \> write \> read \> readm \\
  2284.            \end{tabbing}
  2285.  
  2286.    \end{description}
  2287.            
  2288. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2289. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2290.  
  2291. \section{Input and Output}
  2292.  
  2293.    There are two types if I/O in \RLaB\ .
  2294.  
  2295. \begin{enumerate}
  2296.   \item  Raw data, such as matrices, lists, and strings. In this case
  2297.    the formatting is irrelevant.
  2298.   \item  Formatted I/O, such as data from  other programs, and
  2299.    formatted output intended for reports and such.
  2300. \end{enumerate}
  2301.  
  2302.    In either case file names, or file-handles, are the same. A
  2303.    file-handle is {\em always} a string, either a string constant, a
  2304.    string variable, or a string expression. For example:
  2305.  
  2306. \begin{verbatim}
  2307. > write ("file.rd", A);
  2308.  
  2309. > f = "file.rd"; write (f, A);
  2310.  
  2311. > write ("file" + ".rd", A);
  2312. \end{verbatim}
  2313.  
  2314.    are all equivalent. 
  2315.  
  2316.    There are three special file-handles in \RLaB\ ; they are:
  2317.    \verb+"stdin"+, \verb+"stdout"+, and \verb+"stderr"+.
  2318.  
  2319.    \verb+"stdin"+ is connected to \RLaB's standard input, usually the
  2320.    keyboard. \verb+"stdout"+ is connected to \RLaB's standard output,
  2321.    usually the screen. And \verb+"stderr"+ is connected to the
  2322.    standard error, again, usually the screen.
  2323.  
  2324.    Files are automatically opened by the functions that perform input
  2325.    or output. In most cases the files will automatically be closed
  2326.    after the function has completed its task. The following will
  2327.    force a file closure after their task is complete: \verb+rfile+,
  2328.    \verb+load+, \verb+read+, and \verb+readm+.
  2329.  
  2330.    However, \verb+write+, \verb+writem+, \verb+fprintf+, and
  2331.    \verb+getline+ will leave their files open after completion, so
  2332.    that they may be used subsequently without complicated file
  2333.    positioning operations.
  2334.  
  2335.    \RLaB\ has another special type of file-handle. When a string,
  2336.    starting with a `\verb+|+' is used as a file-handle, a process is
  2337.    created. Either the sub-process input, or output is connected to
  2338.    \RLaB\ through the file-handle. For example:
  2339.  
  2340. \begin{verbatim}
  2341. > output = "| sort";
  2342. > for (i in 5:1:-1) { fprintf (output, "%i\n", i); } close (output);
  2343. 1
  2344. 2
  2345. 3
  2346. 4
  2347. 5
  2348. \end{verbatim}
  2349.  
  2350.    If the \verb+fprintf+ output were not sent to the Unix program
  2351.    \verb+sort+, you would expect the output to appear in descending
  2352.    order. In fact, \verb+fprintf+ does write the output in descending
  2353.    order, to \verb+sort+. Then, \verb+sort+ re-orders its input, and
  2354.    writes it to \verb+stdout+. The same trick works in reverse;
  2355.    functions that expect input can get it from a sub-process. A good
  2356.    example is \verb+getline+:
  2357.  
  2358. \begin{verbatim}
  2359. > input = "| ls -la *.[ch]";
  2360. > fsum = 0;
  2361. > while (length (ans = getline (input))) { fsum = fsum + ans.[5]; } fsum
  2362.  fsum =
  2363.    943083
  2364. > close (input);
  2365. \end{verbatim}
  2366.  
  2367.    In this instance we used the sub-process capability to determine
  2368.    the number of bytes of C source code, and header files exist in the
  2369.    current working directory. The sub-process performs the long
  2370.    listing, and getline parses this input into numbers and strings.
  2371.    The $5^{th}$ column of the \verb+ls -la+ output is the number of
  2372.    bytes in each file.
  2373.  
  2374. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2375. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2376.  
  2377. \section{Plotting}
  2378.  
  2379.    There are two available methods for plotting data from within
  2380.    \rlab. Probably the most desirable is the usage of the builtin
  2381.    plotting library, Plplot. The second method involves the usage of
  2382.    \rlab's I/O abilities (piping) to send data and commands to another
  2383.    running process - Gnuplot, for example.  A fairly extensive
  2384.    example of this second method is provided in the \rlab source
  2385.    distribution in the file \verb+misc/gnu_plot.r+. We shall focus
  2386.    on the builtin plotting capability.
  2387.  
  2388.    There are two new terms you must learn to understand plotting -
  2389.    plot-window, and sub-plot. The plot window is manifested on the
  2390.    plot-device, such as a Tektronix screen, X-window display, or a
  2391.    printer. \rlab will allow you to have multiple plot-windows, if
  2392.    your display device will support it. X-windows supports multiple
  2393.    plot-windows, but a Tektronix display, or DOS display will not.
  2394.  
  2395.    The next term is sub-plot. Each plot-window can have 1 or more
  2396.    sub-plots. The layout of the sub-plots is determined when
  2397.    \verb+pstart+ is called.
  2398.  
  2399.    Regardless of the number of plot-windows and sub-plots, there can
  2400.    only be one {\em current} plot-window, and one {\em current}
  2401.    sub-plot within the current plot-window. Each plot related function
  2402.    will only work on the current sub-plot in the current plot-window.
  2403.    This way the majority of the plot functions are the same,
  2404.    regardless of the output device. The current sub-plot is always the
  2405.    {\em next} plot. As soon as a plot function is used that actually
  2406.    draws the plot on the plot-device, such as \verb+plot+,
  2407.    \verb+plot3+ or \verb+plhist+, the current sub-plot is incremented.
  2408.    Therefore, all functions that effect the appearance of a plot must
  2409.    be used before the plot is drawn.
  2410.  
  2411. \subsection{2-D Plotting}
  2412.    
  2413.    To plot some data with a minimum of effort do:
  2414.  
  2415. \begin{verbatim}
  2416. > data = (0:pi:.1)';
  2417. > data[;2] = cos (2*pi*data*3);
  2418. > pstart (,,"xwin");
  2419. > plot (data);
  2420. \end{verbatim}
  2421.  
  2422.    The \verb+pstart+ function was called with the default sub-plot
  2423.    definition (1 subplot), and the X-windows driver as the display
  2424.    device. The \verb+plot+ function accepts matrices, or lists as
  2425.    arguments and plots the columns of a matrix, or the columns of each
  2426.    matrix of a list.
  2427.  
  2428.    Now for a slightly more complex example.
  2429.  
  2430. \begin{verbatim}
  2431. > t = (0:10:.05)';
  2432. > x = exp (-0.5*t) .* (cos (2*pi*3*t) + sin (2*pi*7*t));
  2433. > X = fft (x);
  2434. > rfile faxis
  2435. > freq = faxis (X, .05, 3);
  2436. > mag = abs (X);
  2437. > rfile angle
  2438. > phase = angle (X);
  2439. > pstart (1,2,"xwin");
  2440. >
  2441. > ptitle ("Magnitude of FFT")
  2442. > xlabel ("Frequency (Hertz)");
  2443. > plot ([freq,mag]);
  2444. >
  2445. > ptitle ("Angle (atan2(imag/real)) of FFT")
  2446. > xlabel ("Frequency (Hertz)");
  2447. > ylabel ("Angle (radians)");
  2448. > plot ([freq,phase]);
  2449. > plprint ("p3.ps");
  2450. \end{verbatim}
  2451.  
  2452. \vskip 1cm
  2453.  
  2454. \begin{figure}[htbp]
  2455.   \begin{picture}(350,350)(0,50) % (x-size, y-size) (x-shift, y-shift)
  2456.     \special{psfile=p3.ps
  2457.              angle=90 hscale=60 vscale=60 voffset=40 hoffset=460}
  2458.     \end{picture}
  2459.     \caption{Example Plot \label{p1}}
  2460. \end{figure}
  2461.  
  2462.    In this example we create a plot-window with two subplots so that
  2463.    we can display related information on the same plot-window. The
  2464.    arguments to \verb+pstart+ specify that there will be 1 plot in the
  2465.    horizontal direction, and 2 plots in the vertical direction, thus
  2466.    creating 2 sub-plots. The first \verb+ptitle+ and \verb+xlabel+
  2467.    function calls effect the first sub-plot. The first call to
  2468.    \verb+plot+ creates the first sub-plot. The subsequent calls to
  2469.    \verb+ptitle+, \verb+xlabel+ and \verb+ylabel+ effect the second
  2470.    sub-plot, and the last call to \verb+plot+ creates the second
  2471.    sub-plot. 
  2472.  
  2473.    The last line is a call to \verb+plprint+. The \verb+plprint+
  2474.    function creates a file that contains a copy of the contents of the
  2475.    current plot-window. The default hardcopy device for \verb+plprint+
  2476.    is Postscript, but color Postscipt, Xfig, plmeta, and HP-LJII can
  2477.    also be specified. The output from \verb+plprint+ is presented in
  2478.    Figure~\ref{p1}.  
  2479.  
  2480. \subsection{Histograms}
  2481.  
  2482.    Histograms can be plotted quite easily. At present the histogram
  2483.    plotting function, \verb+plhist+, will plot histograms of the
  2484.    columns of a matrix. For example:
  2485.  
  2486. \begin{verbatim}
  2487. > // Create data
  2488. > rand("normal", 0, pi);
  2489. > r = rand(2000,1);
  2490. >
  2491. > // Create plot
  2492. > ptitle("Histogram, 30 Bins");
  2493. > plhist (r, 30);
  2494. \end{verbatim}
  2495.  
  2496. \begin{figure}[htbp]
  2497.   \begin{picture}(350,300)(0,50) % (x-size, y-size) (x-shift, y-shift)
  2498.     \special{psfile=p5.ps
  2499.              angle=90 hscale=60 vscale=60 voffset=40 hoffset=460}
  2500.     \end{picture}
  2501.     \caption{Example Histogram Plot \label{p5}}
  2502. \end{figure}
  2503.  
  2504.    Figure~\ref{p5} contains the Postscript output from the previous
  2505.    example. 
  2506.  
  2507. \subsection{3-D Plotting}
  2508.  
  2509.    Plotting 3-dimensional data is quite straightforward, and very
  2510.    similar to the steps used for plotting 2-dimensional data. We will
  2511.    begin with an example:
  2512.  
  2513. \begin{verbatim}
  2514. > // Create the data
  2515. > X = -2:2:.2;
  2516. > Y = X;
  2517. > Z = [];
  2518. > for (i in 1:X.n) { 
  2519. >   for (j in 1:Y.n) { 
  2520. >     Z[i;j] = X[i] * exp (-X[i]^2 - Y[j]^2);
  2521. >   }
  2522. > }
  2523. > // Make the plot
  2524. > pstart(,,"xwin");
  2525. > plwid(4);
  2526. > ptitle("Sample 3-D Plot");
  2527. > xlabel("X-Axis");
  2528. > ylabel("Y-Axis");
  2529. > zlabel("Z-Axis");
  2530. > plmesh( << x = X; y = Y; z = Z >> );
  2531. > plprint("3d.ps");
  2532. \end{verbatim}
  2533.  
  2534. \begin{figure}[htbp]
  2535.   \begin{picture}(300,350)(0,120) % (x-size, y-size) (x-shift, y-shift)
  2536.     \special{psfile=3d.ps
  2537.              angle=90 hscale=80 vscale=80 voffset=40 hoffset=530}
  2538.     \end{picture}
  2539.     \caption{Example 3D Plot \label{p3d}}
  2540. \end{figure}
  2541.  
  2542.    The output from the plprint command appears in
  2543.    Figure~\ref{p3d}. Now we must take a minute and explain the data
  2544.    passed as input to \verb+plot3+. Three dimensional plots have two
  2545.    independent variables (vectors), \verb+x+, and \verb+y+. The
  2546.    dependent variable \verb+z+ (a matrix) is a function of both
  2547.    \verb+x+ and \verb+y+ and has row dimension the length of \verb+x+
  2548.    and column dimension the length \verb+y+. This storage scheme for
  2549.    three-dimensional data is economical in terms of memory, and allows
  2550.    the user some extra flexibility. Thus, the argument to \verb+plot3+
  2551.    is a list with three elements: \verb+x+, \verb+y+, and
  2552.    \verb+z+. \verb+plot3+ can accept up to three distinct lists for
  2553.    plotting.
  2554.  
  2555.    The same plot-functions: \verb+ptitle+, \verb+xlabel+, and
  2556.    \verb+ylabel+ can be used with 3-dimensional plots. Additionally,
  2557.    \verb+zlabel+ can be used to add labels to the \verb+z+ axis.
  2558.  
  2559.    The next example (Figure~\ref{p6}) demonstrates more plotting
  2560.    capabilities - including: changing fonts and pen widths, multiple
  2561.    plots per page and annotating a plot. Note that the calls to
  2562.    \verb+plptex+ are made {\em after} the \verb+plot+ calls. since
  2563.    \verb+plptex+ uses the plot coordinates to place text on the graph,
  2564.    the plot must be created first.
  2565.  
  2566. \begin{verbatim}
  2567. //
  2568. // Demonstrate the effect of adding terms to a Fourier expansion
  2569. //
  2570.  
  2571. // We want to approximate a square wave...
  2572. // The Fourier Series for a square wave is a 
  2573. // sum of odd harmonics - we will demonstrate.
  2574. // Start up a plot window...
  2575.  
  2576. pstart(2,2, "xwin");
  2577.  
  2578. // Compute the 1st term in the Fourier series and plot.
  2579.  
  2580. t = (0:10:.1)';
  2581. y = sin (t);
  2582.  
  2583. ptitle ("Fundamental Frequency");
  2584. plwid(10);
  2585. plfont(1);
  2586. plot ( [t,y] );
  2587. plptex ("Pen width = 10", 4, 0.4);
  2588. plptex ("Font = 1 (Normal)", 4, 0.1);
  2589. pause ();
  2590.  
  2591. // Now add the third harmonic to the fundamental, and plot.
  2592.  
  2593. y = sin (t) + sin (3*t)/3;
  2594.  
  2595. ptitle ("1st and 3rd Harmonics");
  2596. plwid(7);
  2597. plfont(4);
  2598. plot ( [t,y] );
  2599. plptex ("Pen width = 7", 4, 0.4);
  2600. plptex ("Font = 4 (Script)", 4, 0.1);
  2601. pause ();
  2602.  
  2603. // Now use the first, third, fifth, seventh, and ninth harmonics.
  2604.  
  2605. y = sin (t) + sin (3*t)/3 + sin (5*t)/5 + sin (7*t)/7 + sin (9*t)/9;
  2606. ptitle ("1st, 3rd, 5th, 7th, 9th Harmonics");
  2607. plwid(4);
  2608. plfont(3);
  2609. plot ( [t,y] ); 
  2610. plptex ("Pen width = 3", 4, 0.4);
  2611. plptex ("Font = 3 (Italic)", 4, 0.1);
  2612. pause ();
  2613.  
  2614. //
  2615. // Now create a matrix with rows that represent adding
  2616. // more and more terms to the series.
  2617. // 
  2618.  
  2619. t = (0:3.14:.02);
  2620. y = zeros(10,max(size(t)));
  2621. x = zeros(size(t));
  2622.  
  2623. for (k in 1:19:2)
  2624. {
  2625.   x = x + sin(k*t)/k; 
  2626.   y[(k+1)/2;] = x;
  2627. }
  2628.  
  2629. //
  2630. // Now make a nice 3-D plot that shows the effect
  2631. // of adding more and more terms to the series.
  2632. //
  2633.  
  2634. plfont (2);
  2635. plwid(1);
  2636. ptitle ("Square Wave via Fourier Series");
  2637. ylabel ("No. Terms");
  2638. plaz (140);
  2639. plot3 (<< x = t; y=1:10; z=y' >>);
  2640. plptex ("Pen width = 1", -1, 4.5);
  2641. plptex ("Font = 2 (Roman)", -1, 3.8);
  2642. plprint ("p6.ps");    // Make hardcopy (Postscript default).
  2643. \end{verbatim}
  2644.  
  2645. \begin{figure}[htbp]
  2646.   \begin{picture}(500,450)(0,50) % (x-size, y-size) (x-shift, y-shift)
  2647.     \special{psfile=p6.ps
  2648.              angle=90 hscale=70 vscale=80 voffset=40 hoffset=500}
  2649.     \end{picture}
  2650.     \caption{Square Wave Plot Example \label{p6}}
  2651. \end{figure}
  2652.  
  2653. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2654. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2655.  
  2656. \clearpage
  2657. \newpage
  2658.  
  2659. \section{Summary}
  2660.  
  2661.    \Rlab\ can do quite a few things that we have not covered here. The
  2662.    reference manual or the online help should be consulted for more
  2663.    detailed descriptions of language and function behavior. We will
  2664.    close out this primer with a listing of the currently available
  2665.    function (both built-in and user-functions).
  2666.  
  2667. \begin{verbatim}
  2668. > what ()
  2669. abs           epsilon       log           plot          solve         
  2670. acos          error         log10         plot3         sort          
  2671. acosh         eval          logspace      plprint       sprintf       
  2672. all           exist         lu            plptex        sqrt          
  2673. any           exp           lyap          plstyle       srand         
  2674. asin          eye           matrix        plwid         std           
  2675. asinh         factor        max           printf        strsplt       
  2676. atan          fft           maxi          printmat      strtod        
  2677. atan2         filter        mean          prod          sum           
  2678. atanh         find          members       pstart        svd           
  2679. backsub       finite        min           ptitle        sylv          
  2680. balance       fix           mini          pwin          symm          
  2681. cd            floor         mod           qr            system        
  2682. ceil          format        nan           rand          tan           
  2683. chol          fprintf       norm          rank          tanh          
  2684. class         fvscope       num2str       rcond         tic           
  2685. clear         getb          ode           read          tmp_file      
  2686. clearall      getenv        ones          readb         toc           
  2687. close         getline       open          readm         trace         
  2688. compan        hess          pause         real          tril          
  2689. complement    hilb          pclose        redit         triu          
  2690. conj          ifft          pend          replot        type          
  2691. cos           imag          plalt         reshape       union         
  2692. cosh          inf           plaspect      round         what          
  2693. cross         input         plaxis        save          who           
  2694. cumprod       int           plaz          scalar        whos          
  2695. cumsum        int2str       plegend       schord        write         
  2696. det           intersection  plfont        schur         writeb        
  2697. diag          inv           plgrid        set           writem        
  2698. diary         isempty       plgrid3       show          xlabel        
  2699. diff          isinf         plhist        showpwin      ylabel        
  2700. disp          isnan         plhistx       sign          zeros         
  2701. dot           issymm        plhold        sin           zlabel        
  2702. eig           length        plhold_off    sinh                        
  2703. eign          linspace      plimits       size                        
  2704. eigs          load          plmesh        sizeof                      
  2705. > quit
  2706. \end{verbatim}
  2707.  
  2708. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2709. %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
  2710. \end{document}
  2711.